如何从变量运行脚本命令? [英] How to run script commands from variables?
问题描述
我尝试使用管道运行命令.
I tried to run commands using pipes.
基本:
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
工作.
是否可以在不创建执行脚本的情况下执行更复杂的命令?
Is there a way to execute more complex commands without creating a script for execution?
推荐答案
您正在演示Shell与内核之间的区别.
You're demonstrating the difference between the shell and the kernel.
"ls -l"可通过系统execve()调用执行.您可以man execve
获取详细信息,但这可能对您来说太多了.
"ls -l" is executable by the system execve() call. You can man execve
for details, but that's probably too much detail for you.
"ls -l | grep e"需要shell解释才能设置管道.在不使用外壳的情况下,"|"字符只是作为ls的参数传递到execve()中.这就是为什么您看到没有这样的文件或目录"错误的原因.
"ls -l | grep e" needs shell interpretation to set up the pipe. Without using a shell, the '|' character is just passed into execve() as an argument to ls. This is why you see the "No such file or directory" errors.
解决方案:
cmd="ls -l | grep e"
bash -c "$cmd"
这篇关于如何从变量运行脚本命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!