Shell Scripting – Handling Spaces in Variable Assignments

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, the var command with =23 as argument (except in zsh where =something is a special operator that expands to the path of the something command. Here, you'd likely to get an error as 23 is unlikely to be a valid command name).
  • var= 23: an assignment var= followed by a command name 23. That's meant to execute 23 with var= passed to its environment (var environment variable with an empty value).
  • var = 23, var command with = and 23 as argument. Try with echo = 23 for instance.

Csh family

csh and tcsh. Variable assignments there are with the set 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 the var=23 command.
  • var =23 is invoking the var command with =23 as argument.
  • var= 23 is invoking the var= command with 23 as argument
  • var = 23 is invoking the var command with = and 23 as arguments.

Rc family

That's rc, es and akanga. In those shells, variables are arrays and assignments are with var = (foo bar), with var = foo being short for var = (foo) (an array with one foo element) and var = short for var = () (array with no element, use var = '' or var = ('') 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 to var = (23) to assign an array with one element being 23.

Fish

In fish, the variable assignment syntax is set var value1 value2. Like in rc, variables are arrays.

So the behaviour would be the same as with csh, except that fish won't let you run a command with a = in its name. If you have such a command, you need to invoke it via sh for instance: sh -c 'exec weird===cmd'.

So all var=23 and var= 23 will give you an error, var =23 will call the var command with =23 as argument and var = 23 will call the var command with = and 23 as arguments.