5

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!

0

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

2 Comments

Can you elaborate on "better and safer"?
You need unset -f cmd to unset the function. Not that you need to, since you can just redefine it.
1

To execute the content of your variable $cmd you have to use eval:

cnt=$(eval $cmd)

1 Comment

Yes, seems so. That is not the case if there is no pipe. Interesting....
-1

Please use this command:-

cmd= ps aux | grep -v grep

when we want to use o/p from other command we need to use actute (`) instead of double quotes (")

Thanks

1 Comment

But they didn't want the output of the command to cmd, just the command itself. There's the command substitution actually running it on the following line.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.