Bash: execute variable contents including tube

#!/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 the command line, as I have in the second part? Think the problem is in the pipe. Tried to run away, but it didnโ€™t help. Get some snytax ps error.

Thanks!

+5
source share
2 answers

Using eval is not recommended here. This can lead to unexpected results, especially when variables can be read from unreliable sources (see BashFAQ / 048 - Accounting team and security issues .

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

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

and use it in a script like

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

Also, a good reading would be to find out why storing commands in a variable is not a good idea and has many potential errors - BashFAQ / 050 - I try to enter a command into a variable, but difficult cases always fail!

+5
source

You need eval :

 ret=$(eval "$cmd") 
+3
source

Source: https://habr.com/ru/post/1274505/


All Articles