Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When and how do bash determine whether the input line is an assignment?

If I type in the following two commands:

i=1
var$i=2014

I get an error message var1=2014: command not found.

I have found how to make dynamic variable names possible with declare in this SO post, but I still wondering about why that error message is generated. It implies that bash consider var1=2014 as a command/executable name instead of an assignment, and the if this line is an assignment test happened before the $i expansion.

Qustion:

What order does bash follow parsing an input line w.r.t. assignments?

Any recommended reading is also appreciated.

like image 991
Frozen Flame Avatar asked Nov 11 '22 07:11

Frozen Flame


1 Answers

First it checks whether the command looks like an assignment or an ordinary command invocation.

Then it performs variable substitutions, command substitution, etc. It has to do this after determining the type of command line, because variable substitution is different when it goes into an assignment. For instance, there's no word splitting when you write:

var=$variable

but there is word splitting when you write:

command $variable

Finally, after all the substitutions, word splitting, globbing, it executes the command. If it determined it was an assignment, it assigns the variable; otherwise, it executes the command.

In your case, since

var$i=2014

is not valid assignment syntax, the first step determines that it's a command, so the last step tries to execute it as such.

This is greatly simplified.

You should try to avoid using variable variables -- you can almost always achieve the same result more easily using an array.

like image 152
Barmar Avatar answered Nov 15 '22 12:11

Barmar