我有一个包含循环的字符串变量。
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
答案 0 :(得分:7)
您可以添加-c
选项以从参数中读取命令。以下应该有效:
$ loopVariable='for i in 1 2 3 4 5; do echo $i; done'
$ bash -c "$loopVariable"
1
2
3
4
5
来自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.
另一种方法是使用标准输入:
bash <<< "$loopVariable"
关于问题中的更新命令,即使我们更正引用问题,以及未导出变量的事实,您仍然会留下无限循环,因为$i
永远不会更改:
loopValue='while [ "$i" -lt 5 ]; do make -j15 clean && make -j15; done'
i=0 bash -c "$loopValue"
但使用@Kenavoz' answer中的函数几乎总是更好。
答案 1 :(得分:4)
您无需使用While myAns = -1 do
Begin
if IsDisplayed = False then
TDialogService.MessageDialog(AMessage, ADialogType, AButtons, ADefaultButton, 0,
procedure (const AResult: TModalResult)
begin
myAns := AResult;
IsDisplayed := True;
end);
IsDisplayed := True;
Application.ProcessMessages;
End;
Result := myAns;
end;
打开新流程。您可以改为使用Bash函数:
bash -c
请注意,由于没有创建suprocess,因此您无需导出变量以在子进程中使用它们,就像使用function loopVariable {
for i in 1 2 3 4 5; do echo $i; done
}
loopVariable
一样。所有这些都在脚本范围内可用。
<强>输出:强>
bash -c
答案 2 :(得分:2)
loopvariable='for i in 1 2 3 4 5; do echo $i; done'
bash -c "$loopvariable"