gpt4 book ai didi

linux - 如何从变量运行脚本命令?

转载 作者:IT王子 更新时间:2023-10-29 00:19:51 26 4
gpt4 key购买 nike

我尝试使用管道运行命令。

基本:

single="ls -l"
$single

按预期工作

管道:

multi="ls -l | grep e"
$multi
ls: |: No such file or directory
ls: grep: No such file or directory
ls: e: No such file or directory

...不足为奇

bash < $multi

$multi: ambiguous redirect

下次试试

bash $multi
/bin/ls: /bin/ls: cannot execute binary file

只有

echo $multi > tmp.sh
bash tmp.sh

成功了。

有没有一种方法可以在不创建执行脚本的情况下执行更复杂的命令?

最佳答案

您正在演示 shell 和内核之间的区别。

“ls -l”可由系统 execve() 调用执行。您可以 man execve 了解详细信息,但这对您来说可能太详细了。

“ls -l | grep e”需要 shell 解释来设置管道。不使用 shell,'|'字符只是作为 ls 的参数传递给 execve()。这就是您看到“没有这样的文件或目录”错误的原因。

解决方法:

cmd="ls -l | grep e"
bash -c "$cmd"

关于linux - 如何从变量运行脚本命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3469705/

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