开发者

How do I defer backticks (or $()) in a possibly-quoted variable in Bash?

开发者 https://www.devze.com 2023-02-03 15:58 出处:网络
I am trying to get Bash to execute the following minimized example properly: # Runs a开发者_StackOverflow中文版 command, possibly quoted (i.e. single argument)

I am trying to get Bash to execute the following minimized example properly:

# Runs a开发者_StackOverflow中文版 command, possibly quoted (i.e. 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 am trying to get the ability of having commands in quoted strings (or not), and not having any of the command, including nested shell commands through backticks, calculated values, etc., evaluated before run() is called. Is this possible? How can I achieve this?


Well the way to do this sort of thing is to use the eval function associated with an escaped '$' :

function run()
{
    eval $*
}

my_command="ls \$(pwd)"

Escaping '$' as '\$' ensure that my_command will be set to "ls $(pwd)" with no substitution. Then eval will provide the substitution ^^

then

run $my_command
cd ..
run $my_command

prove that you get your functionnality !

my2c

0

精彩评论

暂无评论...
验证码 换一张
取 消