What is the difference between below variables assignments?
var=23
var =23
var= 23
var = 23
Is there any difference in space around the assignment operator?
assignmentshellvariable
What is the difference between below variables assignments?
var=23
var =23
var= 23
var = 23
Is there any difference in space around the assignment operator?
Best Answer
That very much depends on the shell. If we only look at the 4 main shell families (Bourne, csh, rc, fish):
Bourne family
That is the Bourne shell and all its variants and
ksh
,bash
,ash
/dash
,zsh
,yash
.var=23
: that's the correct variable assignment syntax: a word that consists of unquoted letters, digits or underscores followed by an unquoted=
that appears before a command argument (here it's on its own)var =23
, thevar
command with=23
as argument (except inzsh
where=something
is a special operator that expands to the path of thesomething
command. Here, you'd likely to get an error as23
is unlikely to be a valid command name).var= 23
: an assignmentvar=
followed by a command name23
. That's meant to execute23
withvar=
passed to its environment (var
environment variable with an empty value).var = 23
,var
command with=
and23
as argument. Try withecho = 23
for instance.Csh family
csh
andtcsh
. Variable assignments there are with theset var = value
syntax for scalar variables,set var = (a b)
for arrays,setenv var value
for environment variables,@ var=1+1
for assignment and arithmetic evaluation.So:
var=23
is just invoking thevar=23
command.var =23
is invoking thevar
command with=23
as argument.var= 23
is invoking thevar=
command with23
as argumentvar = 23
is invoking thevar
command with=
and23
as arguments.Rc family
That's
rc
,es
andakanga
. In those shells, variables are arrays and assignments are withvar = (foo bar)
, withvar = foo
being short forvar = (foo)
(an array with onefoo
element) andvar =
short forvar = ()
(array with no element, usevar = ''
orvar = ('')
for an array with one empty element).In any case, blanks (space or tab) around
=
are allowed and optional. So in those shells those 4 commands are equivalent and equivalent tovar = (23)
to assign an array with one element being23
.Fish
In
fish
, the variable assignment syntax isset var value1 value2
. Like inrc
, variables are arrays.So the behaviour would be the same as with
csh
, except thatfish
won't let you run a command with a=
in its name. If you have such a command, you need to invoke it viash
for instance:sh -c 'exec weird===cmd'
.So all
var=23
andvar= 23
will give you an error,var =23
will call thevar
command with=23
as argument andvar = 23
will call thevar
command with=
and23
as arguments.