【发布时间】:2020-03-22 01:39:39
【问题描述】:
我在命令名称中使用变量扩展进行测试的示例 bash 脚本:
test_command_w_variable_expansion_in_name.sh:
#!/bin/bash
# Gabriel Staples
# 21 Mar. 2020
echo "PATH = \"$PATH\""
# PATH="$HOME/bin:$PATH"
# echo "PATH = \"$PATH\""
# 1st, create a command in ~/bin to test here
mkdir -p ~/bin
echo -e "#!/bin/bash\necho \"This is a test script found in ~/bin.\"" > ~/bin/gs_test_script
chmod +x ~/bin/gs_test_script
# 1)
# command: `echo`
CMD_PREFIX="ec"
${CMD_PREFIX}ho "hey" # works
# exec "${CMD_PREFIX}ho" "hey" # works, but then prevents the code below from running!
# eval "${CMD_PREFIX}ho" "hey" # does NOT work, but also throws no error
# 2)
# command: `gs_test_script` from ~/bin
CMD_PREFIX="gs_test"
~/bin/gs_test_script # works!
gs_test_script # works!
${CMD_PREFIX}_script # works!
输出:
$ ./test_command_w_variable_expansion_in_name.sh
PATH = "/home/gabriel/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin"
hey
This is a test script found in ~/bin.
This is a test script found in ~/bin.
This is a test script found in ~/bin.
问题:
-
现在,如果我取消注释这一行:
# exec "${CMD_PREFIX}ho" "hey" # works, but then prevents the code below from running!,它下面的代码将不再运行,而是得到这个输出!请注意,我不再收到This is a test script found in ~/bin.的 3 份打印输出 为什么?$ ./test_command_w_variable_expansion_in_name.sh PATH = "/home/gabriel/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin" hey hey 另外,它下面的
eval命令也不起作用。如果我取消注释该行,我会得到与上面发布的完全相同的错误输出,它仍然不会像应有的那样执行我对gs_test_script的调用三次。为什么?
【问题讨论】:
-
除非您了解它们的作用,否则不要使用
exec或eval。eval因引起非常奇怪(有时是危险的)错误而声名狼藉。将命令(或命令的一部分)放入变量中也很棘手,如果可能的话,最好避免使用它。见BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail!