如何在 Bash 中可能引用的变量中延迟反引号(或 $())?

发布于 2024-10-12 02:17:32 字数 449 浏览 4 评论 0原文

我试图让 Bash 正确执行以下最小化示例:

# Runs a 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)

总而言之,我试图获得在带引号的字符串(或不带引号)中包含命令的能力,并且不包含任何命令,包括通过反引号嵌套的 shell 命令,计算值等,在调用 run() 之前评估。这可能吗?我怎样才能实现这个目标?

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

# Runs a 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

彩扇题诗 2024-10-19 02:17:32

执行此类操作的方法是使用与转义 '$' 关联的 eval 函数:

function run()
{
    eval $*
}

my_command="ls \$(pwd)"

将 '$' 转义为 '\$' 确保 my_command 将设置为“ls $(pwd)”而不进行替换。然后 eval 将提供替换 ^^

然后

run $my_command
cd ..
run $my_command

证明您获得了功能!

我的2c

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文