[英]Using spaces in bash scripts
I have a script foo.sh 我有一个脚本foo.sh
CMD='export FOO="BAR"'
$CMD
echo $FOO
It works as expected 它按预期工作
>./foo.sh
"BAR"
Now I want to change FOO variable to BAR BAR
. 现在我想将FOO变量更改为
BAR BAR
。 So I get script 所以我得到了脚本
CMD='export FOO="BAR BAR"'
$CMD
echo $FOO
When I run it I expect to get "BAR BAR"
, but I get 当我运行它时,我期望得到
"BAR BAR"
,但是我得到
./foo.sh: line 2: export: `BAR"': not a valid identifier
"BAR
How I can deal with that? 我该如何处理?
You should not use a variable as a command by just calling it (like in your $CMD
). 您不应仅通过调用变量(如在
$CMD
)将其用作命令。 Instead, use eval
to evaluate a command stored in a variable. 而是使用
eval
评估存储在变量中的命令。 Only by doing this, a true evaluation step with all the shell logic is performed: 只有这样做,才能执行所有外壳程序逻辑的真实评估步骤:
eval "$CMD"
(And use double quotes to pass the command to eval
.) (并使用双引号将命令传递给
eval
。)
Just don't do that. 只是不要那样做。
And read Bash FAQ #50 并阅读Bash常见问题#50
- I'm trying to save a command so I can run it later without having to repeat it each time
我正在尝试保存命令,以便以后可以运行而不必每次都重复
If you want to put a command in a container for later use, use a function.
如果要将命令放在容器中供以后使用,请使用一个函数。 Variables hold data, functions hold code.
变量保存数据,函数保存代码。
pingMe() { ping -q -c1 "$HOSTNAME" } [...] if pingMe; then ..
The proper way to do that is to use an array instead: 正确的方法是使用数组:
CMD=(export FOO="BAR BAR")
"${CMD[@]}"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.