Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: execute content of variable including pipe [duplicate]

Tags:

bash

#!/bin/bash

# 1st part
ret=$(ps aux | grep -v grep)    # thats OK 
echo $ret

# 2nd part
cmd="ps aux | grep -v grep"     # a problem with the pipe | 
ret=$($cmd)         
echo $ret

How can I use a command-string as I have in the 2nd part? Think the pipe is the problem. Tried to escape it but it did not help. Get some snytax error of ps.

Thanks!

like image 294
chris01 Avatar asked Jan 04 '18 15:01

chris01


People also ask

Can you pipe to a variable in bash?

Piping read to assign a value to a variable, the shell creates a new sub-shell where the piped command is executed. Therefore, the value is lost, and the variable cannot be used. However, when we use the lastpipe option in the recent versions of bash, we can pipe the output of a command, such as echo, to read.

What is $@ in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc.

What is &2 in bash script?

and >&2 means send the output to STDERR, So it will print the message as an error on the console. You can understand more about shell redirecting from those references: https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Redirections.


2 Answers

You need eval:

ret=$(eval "$cmd")
like image 128
Jack Avatar answered Dec 16 '22 18:12

Jack


Using eval is not recommended here. It can lead to unexpected results, especially when variables can be read from untrusted sources (See BashFAQ/048 - Eval command and security issues.

You can solve this in a simple way by defining and calling a function as below

ps_cmd() {
    ps aux | grep -v grep
}

and use it in the script as

output="$(ps_cmd)"
echo "$output"

Also a good read would be to see why storing commands in a variable is not a good idea and has a lot of potential pitfalls - BashFAQ/050 - I'm trying to put a command in a variable, but the complex cases always fail!

like image 22
Inian Avatar answered Dec 16 '22 19:12

Inian