I have a string variable which contains a loop.
loopVariable="for i in 1 2 3 4 5 do echo $i done"
bash: for i in 1 2 3 4 5 do echo $i done: No such file or directory
loopValue="while [ $i -lt 5 ]; do make -j15 clean && make -j15 done"
bash -c @loopValue
bash: -c: line 0: syntax error near unexpected token `done'
[: -c: line 1: syntax error: unexpected end of file
You can add the
-c option to read the command from an argument. The following should work:
$ loopVariable='for i in 1 2 3 4 5; do echo $i; done' $ bash -c "$loopVariable" 1 2 3 4 5
from 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.
Another way is to use the standard input:
bash <<< "$loopVariable"
Regarding the updated command in the question, even if we correct the quoting issues, and the fact that the variable is not exported, you are still left with an infinite loop since
$i never changes:
loopValue='while [ "$i" -lt 5 ]; do make -j15 clean && make -j15; done' i=0 bash -c "$loopValue"
But it would almost always be better to use a function as in @Kenavoz' answer.