如何将字符串传递给bash命令作为参数

mr_*_*eet 2 bash shell

我有一个包含循环的字符串变量.

loopVariable="for i in 1 2 3 4 5 do echo $i done"
Run Code Online (Sandbox Code Playgroud)

我想将此变量传递给shell脚本中的bash命令.但我总是得到一个错误

bash $loopVariable
Run Code Online (Sandbox Code Playgroud)

我也试过了

bin/bash $loopVariable
Run Code Online (Sandbox Code Playgroud)

但它也行不通.Bash处理字符串给我一个错误.但理论上它执行它.我不知道我做错了什么

bash: for i in 1 2 3 4 5 do echo $i done: No such file or directory
Run Code Online (Sandbox Code Playgroud)

我也尝试过使用while循环这种方法.但得到同样的错误

i=0 
loopValue="while [ $i -lt 5 ]; do make -j15 clean && make -j15 done"
bash -c @loopValue
Run Code Online (Sandbox Code Playgroud)

当我使用bash -c"@loopValue"时,我得到以下错误

bash: -c: line 0: syntax error near unexpected token `done'
Run Code Online (Sandbox Code Playgroud)

当我使用时,只需使用bash -c @loopValue

[: -c: line 1: syntax error: unexpected end of file
Run Code Online (Sandbox Code Playgroud)

use*_*001 7

您可以添加-c选项以从参数中读取命令.以下应该有效:

$ loopVariable='for i in 1 2 3 4 5; do echo $i; done'
$ bash -c "$loopVariable"
1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)

来自man bash:

  -c         If the -c option is present, then commands are read from  the
             first non-option argument command_string.  If there are argu?
             ments after the command_string,  they  are  assigned  to  the
             positional parameters, starting with $0.
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用标准输入:

bash <<< "$loopVariable"
Run Code Online (Sandbox Code Playgroud)

关于问题中的更新命令,即使我们更正引用问题,以及未导出变量的事实,您仍然会留下无限循环,因为$i永远不会更改:

loopValue='while [ "$i" -lt 5 ]; do make -j15 clean && make -j15; done'
i=0 bash -c "$loopValue"
Run Code Online (Sandbox Code Playgroud)

但是在@Kenavoz的回答中使用函数几乎总是更好.