How to run script commands from variables?

I tried to run commands using pipes.

The main

single="ls -l" $single 

which works as expected

<power> 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 

... not surprising

 bash < $multi $multi: ambiguous redirect 

next attempt

 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 to execute?

+7
command-line linux bash shell
source share
3 answers

You demonstrate the difference between the shell and the core.

"ls -l" is executed by calling systemveve (). You can man execve for details, but this is probably too many details for you.

"ls -l | grep e" requires shell interpretation to configure the pipe. Without shell, '|' the character is simply passed to execve () as an argument to ls. This is why you see the error "There is no such file or directory."

Decision:

 cmd="ls -l | grep e" bash -c "$cmd" 
+11
source share

To do this, heredoc needs to do this correctly. In response to a POSIX-compatible way to see if a function is defined in sh script , I described in detail how to read a script in a variable, programmatically analyze it for information and / or modify it as needed, then execute it from another script function or shell. This is basically what you are trying to do, and heredoc makes this possible, since it provides a file descriptor:

 % multi='ls -l | grep e' % sh <<_EOF_ > ${multi} > _EOF_ < desired output > 

This will solve your simple example. See my other answer for more.

-Mike

0
source share

when you want to run commands using pipes, just run it. Never add a command to a variable or try to run it. Just follow it

ls -l |grep

If you want to capture the output, use $ ()

var=$(ls -l |grep .. )

-3
source share

All Articles