在一个文件中,有一些像这样的多命令行:
cd /home/user; ls
在 bash 脚本中,我想执行这些命令,向最后一个命令添加一些参数。例如:
cd /home/user; ls -l *.png
我认为做这样的事情就足够了:
#!/bin/bash
commandLine="$(cat theFileWithCommandInside) -l *.png"
$commandLine
exit 0
但是它说:
/home/user;: No such file or directory
换句话说,“;”字符不再表示“命令结束”:shell 正在尝试查找名为“user”的目录;在主文件夹中...
我试图替换“;”与“&&”,但结果是一样的。
最佳答案
你的问题的重点是执行存储在字符串中的命令。有数千种方法可以间接执行。但最终,bash 必须参与进来。
那么为什么不显式调用 bash 来完成这项工作呢?
bash -c "$commandLine"
来自文档:
-c string
If the -c option is present, then commands are read from string. If there are arguments after the string, they are assigned to the positional parameters, starting with $0.
关于linux - Bash:在脚本中执行多命令行字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29013319/