Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

linux - How to run script commands from variables?

I tried to run commands using pipes.

Basic:

single="ls -l"
$single

which works as expected

Pipes:

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

...no surprise

bash < $multi

$multi: ambiguous redirect

next try

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

Only

echo $multi > tmp.sh
bash tmp.sh

worked.

Is there a way to execute more complex commands without creating a script for execution?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're demonstrating the difference between the shell and the kernel.

"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" 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.

Solution:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...