Kvyatkovsky Sergey Kvyatkovsky Sergey - 1 month ago 7
Bash Question

how to pass string to bash command as a parameter

I have a string variable which contains a loop.

loopVariable="for i in 1 2 3 4 5 do echo $i done"


I want to pass this variable to a bash command inside the shell script. But i am always getting an error

bash $loopVariable


i've tried also

bin/bash $loopVariable


But it also doesn't work. Bash treats the string giving me an error. But theoretically it execute it. I am not sure what am i doing wrong

bash: for i in 1 2 3 4 5 do echo $i done: No such file or directory


I have also tried to use this approach using while loop. But getting the same error

i=0
loopValue="while [ $i -lt 5 ]; do make -j15 clean && make -j15 done"
bash -c @loopValue


when I use bash -c "@loopValue" i get following error

bash: -c: line 0: syntax error near unexpected token `done'


and when i use just use bash -c @loopValue

[: -c: line 1: syntax error: unexpected end of file

Answer

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.