如何将字符串传递给bash命令作为参数
问题描述:
我有一个包含循环的字符串变量。如何将字符串传递给bash命令作为参数
loopVariable="for i in 1 2 3 4 5 do echo $i done"
我想将这个变量传递给shell脚本中的bash命令。但我总是得到一个错误
bash $loopVariable
我也试过
bin/bash $loopVariable
但它也不起作用。 Bash对待给我一个错误的字符串。但理论上它执行它。我不知道我做错了什么
bash: for i in 1 2 3 4 5 do echo $i done: No such file or directory
我也尝试过使用while循环使用这种方法。但得到了同样的错误
i=0
loopValue="while [ $i -lt 5 ]; do make -j15 clean && make -j15 done"
bash -c @loopValue
当我使用bash -c “@loopValue” 我知道下面的错误
bash: -c: line 0: syntax error near unexpected token `done'
,当我使用只是使用bash -c @loopValue
[: -c: line 1: syntax error: unexpected end of file
答
您可以添加-c
选项以从参数中读取命令。下面应该工作:
$ loopVariable='for i in 1 2 3 4 5; do echo $i; done'
$ bash -c "$loopVariable"
1
2
3
4
5
从人的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.
另一种方法是使用标准输入:在这个问题
bash <<< "$loopVariable"
关于更新的命令,即使我们更正了引用问题,以及变量未被导出的事实,但是自从0123以来仍然存在无限循环从未改变:
loopValue='while [ "$i" -lt 5 ]; do make -j15 clean && make -j15; done'
i=0 bash -c "$loopValue"
但它几乎总是更好地使用功能为@Kenavoz' answer。
答
loopvariable='for i in 1 2 3 4 5; do echo $i; done'
bash -c "$loopvariable"
答
您不需要使用bash -c
开启新流程。您可以使用bash函数来代替:
function loopVariable {
for i in 1 2 3 4 5; do echo $i; done
}
loopVariable
请注意,由于没有创建suprocess,你不需要导出变量使用它们的子进程作为一个bash -c
。所有这些都在脚本范围内可用。
输出:
1
2
3
4
5
你'while'回路应'而[$ I -lt 5];做make -j15 clean && make -j15; done',(在'done'之前缺少';'''),以及你的bash命令:'bash -c $ loopValue',而不是'bash -c @ loopValue'。 – SLePort
现在它给出'-c:第1行:语法错误:意外的文件结尾' –
我的坏...双引号变量:'bash -c“$ loopValue”' – SLePort