shell - how to pass string to bash command as a parameter -
i have string variable contains loop.
loopvariable="for in 1 2 3 4 5 echo $i done"
i want pass variable bash command inside shell script. getting error
bash $loopvariable
i've tried
bin/bash $loopvariable
but doesn't work. bash treats string giving me error. theoretically execute it. not sure doing wrong
bash: in 1 2 3 4 5 echo $i done: no such file or directory
i have tried use approach using while loop. getting same error
i=0 loopvalue="while [ $i -lt 5 ]; make -j15 clean && make -j15 done" bash -c @loopvalue
when use bash -c "@loopvalue" following error
bash: -c: line 0: syntax error near unexpected token `done'
and when use use bash -c @loopvalue
[: -c: line 1: syntax error: unexpected end of file
you can add -c
option read command argument. following should work:
$ loopvariable='for in 1 2 3 4 5; echo $i; done' $ bash -c "$loopvariable" 1 2 3 4 5
from man bash:
-c if -c option present, commands read first non-option argument command_string. if there argu‐ ments after command_string, assigned positional parameters, starting $0.
another way use standard input:
bash <<< "$loopvariable"
regarding updated command in question, if correct quoting issues, , fact variable not exported, still left infinite loop since $i
never changes:
loopvalue='while [ "$i" -lt 5 ]; make -j15 clean && make -j15; done' i=0 bash -c "$loopvalue"
but better use function in @kenavoz' answer.
Comments
Post a Comment