Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash: pipe-character in variable for command-substitution

Tags:

linux

bash

Can please someone explain, why this is not working??

#!/bin/bash
cmd="ps aux | grep -v grep"
cnt=$($cmd)

I get an error from ps.

error: garbage option

Usage:
  ps [options]
.....

"ps aux" only will be ok - but not with any additional piped commands.

Thanks!

like image 727
chris01 Avatar asked May 03 '17 06:05

chris01


1 Answers

It is better and safer to use function to store a pipeline command as:

unset cmd cnt

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

and use it in command substitution as:

cnt="$(cmd)"

See BASH FAQ on storing command line in a variable

like image 57
anubhava Avatar answered Sep 28 '22 15:09

anubhava