3

For example:

#!/bin/bash
sss='ls -l'
$sss
ttt='a=100'
$ttt

The output of ls is correct, however, the assignment statement will output an error message:

line 5: a=100: command not found

Why the difference?

If assignment is not command, what is it? I mean what is the difference between explicit a=100 and a=100 expanded from variable, I mean, the bash sees the same thing a=100, right? Why they got different interpretation?

3 Answers 3

5

That's because the output from variable expansion is run as a command, precisely get replaced in the command line as if you have inserted the content literally.

Here, you have ttt='a=100', so when you do $ttt next, it will be simple expanded as a=100 and as this would be the command to run being the only parameter present. And the error is due to the obvious fact that this is not a valid command.

You can tack the expansion with some actual-valid command to get the expansion as that command's argument (e.g. echo $ttt), as you can imagine.


If you ever need to do assignments like that, leverage declare:

$ ttt='a=100'

$ declare "$ttt"

$ echo "$a"
100
Sign up to request clarification or add additional context in comments.

Comments

1

If you want to execute code, use a function, not a parameter expansion.

$ sss () { ls -l; }
$ sss
foo.txt bar.txt
$ ttt () { a=100; }
$ ttt
$ printf '%d\n' "$a"
100

Comments

0

Because a=100 is not a command, and you can't evaluate assignments like that.

In order to properly evaluate the assignment try:

eval $ttt

3 Comments

Hi,Thank you for answering. But I got confused, if assignment is not command, what is it? I mean it is still not clear, what is the difference between explicit a=100 and a=100 expanded from variable, I mean, the bash sees the same thing a=100, right? Why it got different interpretation?
It didn't differentiate really. command for shell is one of alias, builtin, function, or an executable file either specified through a path or looked up through the list of directories specified by $PATH. In your case, ls was looked up and found in one of the directories of $PATH, however, a=100 wasn't found. Hence, 'command not found` error.
Why do you suggest eval to a newbie?

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.