0

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?

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

thanks is ((...)) a standard posix thing or is that specific for bash ?
"Fo" -> "For" 1st word 1st paragraph.
@David542, POSIX shell is a subset of Korn and, from pubs.opengroup.org/onlinepubs/9699919799, looks to also handle the ((..)) construct as an extension.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.