Reputation: 110502
In bash script it seems to not allow a space on either side of the =
sign. For example:
# bad
a= "ok"
# bad
a ="ok"
# bad
a = "ok"
# good
a="ok"
Is this the same across all shell
languages, or bash-specific? Out of curiosity, why does it not allow a space next to the assignment operator?
Upvotes: 0
Views: 38
Reputation: 882596
For specific shells, you'll need to look up the documentation for that shell. For bash
, it's a requirement that there be no spaces in that form (note that there are no spaces on either side of the =
):
A variable may be assigned to by a statement of the form
name=[value]
.
One reason why this may be the case is that you can use command-temporal assignments where a variable is set only for the duration of a command:
pax:~> x=314159 ; echo $x
314159
pax:~> x=42 bash -c 'echo $x'
42
pax:~> echo $x
314159
Allowing spaces in the assignment would make it a little difficult to figure out where the assignment finished and where the command started. For example:
x= echo echo hello
Should this set x
to echo
then run echo hello
or should it set x
to ""
and then run echo echo hello
?
If you want your assignment to be nicely formatted with spaces, you can use the ((...))
arithmetic evaluation:
pax:~> (( val = 117 / 3 )) ; echo $val
39
Upvotes: 1