如何解决传递并执行带引号的命令管道作为函数参数
今天遇到了一件很奇怪的事情
我有两个脚本:
错误的.sh:
execute()
{
${@}
}
execute "ls -l | less"
right.sh:
execute()
{
${@}
}
execute ls -l | less
运行 sh wrong.sh
给出以下输出:
ls: less: No such file or directory
ls: |: No such file or directory
运行 sh right.sh
的效果与运行 ls -l | less
的效果相同
我可以知道:
(1) 运行 sh wrong.sh
时会给我错误的输出
(2) 如何修改 execute
函数,使运行 sh wrong.sh
得到与运行 ls -l | less
解决方法
在您的 wrong.sh
调用中,您试图运行一个具有相当不寻常的 12 字节长名称 ls -l | less
(可能实际上存在,例如 /usr/bin/'ls -l | less'
)的命令
如果要将字符串解释为 shell 命令,最简单的方法是:
sh -c "$command_as_string"
所以你的情况
execute()
{
sh -c "$1" # no ${@} if you only intend to ever pass a single string
# or $SHELL -c "$1" if you want the *same* shell as you're calling execute() from
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。