asked in Software by (8.2k points) edited by
0 like 0 dislike
7 views
How I can to run string with values as a command in bash shell in Linux terminal/console? How to execute a bash command stored as a string with quotes?

bash run command stored in string

1 Answer

0 like 0 dislike
answered by (8.2k points) edited by

Have you tried:

eval $cmd

For the follow-on question of how to escape * since it has special meaning when it's naked or in double quoted strings: use single quotes.

Or that would be:

eval "$cmd"

If you want the content of $cmd to be evaluated as shell code.

If you can't guarantee that $cmd won't start with dash/minus (-), which would cause eval in some shells like bash to treat it as an option, instead you may want to run:

eval " $cmd"

That extra leading space won't affect the way the command is parsed and will prevent $cmd from being treated as an option to eval if it starts with -. The eval -- "$cmd" would also work in some shells (including bash) but is not POSIX (IIRC) and wouldn't work in dash or the Bourne shell for instance.

You don't need use eval for even. Just put a dollar sign in front of the string:

cmd="ls"
$cmd

Your answer

Try to answer the question as detailed as possible.
Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
Anti-spam verification:
To avoid this verification in future, please log in or register.

Related questions

0 like 0 dislike
1 answer 6 views
0 like 0 dislike
1 answer 8 views
0 like 0 dislike
1 answer 7 views
0 like 0 dislike
1 answer 6 views
0 like 0 dislike
1 answer 26 views
0 like 0 dislike
1 answer 8 views
0 like 0 dislike
1 answer 27 views
...