gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 09:10:46 24 4
gpt4 key购买 nike

我正在尝试让 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)

总而言之,我正在尝试获得在带引号的字符串中包含命令(或不包含)的能力,而不是在 run() 之前评估任何命令,包括通过反引号、计算值等嵌套的 shell 命令叫做。这可能吗?我怎样才能做到这一点?

最佳答案

做这种事情的方法是使用与转义的 '$' 关联的 eval 函数:

function run()
{
eval $*
}

my_command="ls \$(pwd)"

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

然后

run $my_command
cd ..
run $my_command

证明你得到了你的功能!

我的2c

关于bash - 如何在 Bash 中延迟可能引用的变量中的反引号(或 $())?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4668815/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com