Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment statement stored in a variable causes command not found error in Bash

Tags:

bash

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?

like image 232
user15964 Avatar asked Dec 28 '25 05:12

user15964


1 Answers

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
like image 140
heemayl Avatar answered Dec 30 '25 22:12

heemayl