存储在变量中的赋值语句导致在Bash中找不到命令错误 [英] Assignment statement stored in a variable causes command not found error in Bash
问题描述
例如:
#!/bin/bash
sss='ls -l'
$sss
ttt='a=100'
$ttt
ls
的输出正确,但是,赋值语句将输出错误消息:
The output of ls
is correct, however, the assignment statement will output an error message:
第5行:a = 100:未找到命令
line 5: a=100: command not found
为什么有区别?
如果分配不是命令,那是什么?我的意思是显式的 a = 100
和从变量扩展的 a = 100
有什么区别,我的意思是,bash看到的是相同的 a = 100 代码>,对不对?为什么他们会有不同的解释?
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?
推荐答案
这是因为变量扩展的输出是作为命令运行的,因此就像在字面上直接插入了内容一样,在命令行中被替换了.
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.
在这里,您有 ttt ='a = 100'
,因此当您接下来执行 $ ttt
时,它会简单地扩展为 a = 100
,因为这是要运行的命令,它是唯一存在的参数.该错误是由于明显的事实,即这不是有效的命令.
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.
您可以想象,可以使用一些实际有效的命令来扩展该扩展,以将该扩展作为该命令的参数(例如 echo $ ttt
).
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.
如果您需要进行这样的分配,请利用 declare
:
If you ever need to do assignments like that, leverage declare
:
$ ttt='a=100'
$ declare "$ttt"
$ echo "$a"
100
这篇关于存储在变量中的赋值语句导致在Bash中找不到命令错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!