How to defer backticks (or $ ()) in a possibly specified variable in Bash?

I am trying to get Bash to execute the following example below:

# Runs a command, possibly quoted (ie single argument) function run() { $* } run ls # works fine run "ls" # also works run "ls `pwd`" # also works, but pwd is eagerly evaluated (I want it to evaluate inside run) run "ls \\\`pwd\\\`" # doesn't work (tried other variants as well) 

To summarize, I try to get the opportunity to have the commands in quotation marks (or not) and not have any commands, including nested shell commands through return outputs, calculated values, etc., evaluated before run () is called. Is it possible? How can i achieve this?

+4
source share
1 answer

Well, how to do this, you need to use the eval function associated with escape - '$':

 function run() { eval $* } my_command="ls \$(pwd)" 

Escaping '$' as '\ $' ensures that my_command will be set to "ls $ (pwd)" without replacement. Then eval will provide a replacement ^^

then

 run $my_command cd .. run $my_command 

Prove that you get your functionality!

my2c

+7
source

Source: https://habr.com/ru/post/1335237/


All Articles