cashman04
cashman04

Reputation: 1173

How to pass parts of a command as variable bash?

a="grep ssh | grep -v grep"
ps -ef | $a | awk '{print $2}'

How can I make the above work? I have a section where I need to not just pass the grep term, but possible pass more than one grep term, meaning I need to pass "term1 | grep term2" as a variable.

Edit:

another.anon.coward answer below worked perfectly for me. Thank you sir!

Upvotes: 2

Views: 147

Answers (2)

iamauser
iamauser

Reputation: 11469

If you want just the pid of a process, then use pgrep.

pgrep ssh

You can put this in a bash like the following (a.bash) :

#!/bin/bash
pname=$1
pgrep "$pname"

or if you want ps -ef for other purposes as you've written, following inside a script might work:

pname=$1
ps -ef | grep "$pname" | grep -v grep | awk '{print $2}'  # I would personally prefer this

OR

ps -ef | eval "$pname" | awk '{print $2}'  # here $pname can be "grep ssh | grep -v grep"

change the permission to execute :

chmod a+x a.bash
./a.bash ssh

Upvotes: 2

konsolebox
konsolebox

Reputation: 75458

Create a function instead:

a() {
    grep ssh | grep -v grep
}
ps -ef | a | awk '{print $2}'

The other solution is to use eval but it's unsafe unless properly sanitized, and is not recommended.

a="grep ssh | grep -v grep"
ps -ef | eval "$a" | awk '{print $2}'

Upvotes: 5

Related Questions