如何在 Bash 中可能引用的变量中延迟反引号(或 $())?
我试图让 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
执行此类操作的方法是使用与转义 '$' 关联的 eval 函数:
将 '$' 转义为 '\$' 确保 my_command 将设置为“ls $(pwd)”而不进行替换。然后 eval 将提供替换 ^^
然后
证明您获得了功能!
我的2c
Well the way to do this sort of thing is to use the eval function associated with an escaped '$' :
Escaping '$' as '\$' ensure that my_command will be set to "ls $(pwd)" with no substitution. Then eval will provide the substitution ^^
then
prove that you get your functionnality !
my2c