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

标签 linux bash shell command-line

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

基本:

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/

相关文章:

linux - libnetfilter_queue recv() 函数

linux - dpkg:不可恢复的 fatal error (包 'java-common' 的文件列表文件缺少最后的换行符)

linux - 将目录名称附加到任何文件的递归查找

PythonAnywhere:尝试使用 easygui 模块时出现 Tkinter.py 错误

java - 如何为java进程创建PID文件

bash - 每次输入 kubectl --all-namespaces 的快捷方式

linux - 通过 ssh 杀死远程进程

oracle - 从shell脚本调用oracle存储过程,无需SQLPLUS

linux - Imagemagick 的导入速度慢得令人沮丧

bash - 使用自动 bash 脚本检查 FTP 中是否存在文件