Thursday, October 6, 2022

[SOLVED] How to capture the output of a bash command into a variable when using pipes and apostrophe?

Issue

I am not sure how to save the output of a command via bash into a variable:

PID = 'ps -ef | grep -v color=auto | grep raspivid | awk '{print $2}''

Do I have to use a special character for the apostrophe or for the pipes?

Thanks!


Solution

To capture the output of a command in shell, use command substitution: $(...). Thus:

pid=$(ps -ef | grep -v color=auto | grep raspivid | awk '{print $2}')

Notes

  • When making an assignment in shell, there must be no spaces around the equal sign.

  • When defining shell variables for local use, it is best practice to use lower case or mixed case. Variables that are important to the system are defined in upper case and you don't want to accidentally overwrite one of them.

Simplification

If the goal is to get the PID of the raspivid process, then the grep and awk can be combined into a single process:

pid=$(ps -ef | awk '/[r]aspivid/{print $2}')

Note the simple trick that excludes the current process from the output: instead of searching for raspivid we search for [r]aspivid. The string [r]aspivid does not match the regular expression [r]aspivid. Hence the current process is removed from the output.

The Flexibility of awk

For the purpose of showing how awk can replace multiple calls to grep, consider this scenario: suppose that we want to find lines that contain raspivid but that do not contain color=auto. With awk, both conditions can be combined logically:

pid=$(ps -ef  | awk '/raspivid/ && !/color=auto/{print $2}')

Here, /raspivid/ requires a match with raspivid. The && symbol means logical "and". The ! before the regex /color=auto/ means logical "not". Thus, /raspivid/ && !/color=auto/ matches only on lines that contain raspivid but not color=auto.



Answered By - John1024
Answer Checked By - Clifford M. (WPSolving Volunteer)