I'm writing a bash script where I want to grep the name of a process. This name is the argument when the script is executed.

Normally I can do this ps -ef | grep [w]ord to get the correct processes. How can I have the same effect when the argument to grep (here [w]ord) is something like $1


ps -ef | grep [f]fmpeg

will show lines like this and nothing else

jan 117977 117966 0 20:07 pts/0 00:00:01 ffmpeg ..

when I want the same behavior within a script and make the argument to grep the argument from the script:

ps -ef | grep "$1"

and call it with ./script.sh ffmpeg it will show me the ffmpeg processes (correct) but also the grep and bash process:

jan       117977  117966  0 20:07 pts/0    00:00:01 ffmpeg ..
jan       118566  117021  0 20:14 pts/4    00:00:00 bash ./script.sh ffmpeg
jan       118568  118566  0 20:14 pts/4    00:00:00 grep ffmpeg

I'm not interested in the last two lines of the output

  • Thanks to show us sample input and expected output Commented Mar 23, 2023 at 19:09
  • ps with -f displays the arg lists of the processes (same as ps -o args), not the process name (ps -o comm). To select processes by name (or arg list), use pgrep (or pgrep -f). Commented Mar 23, 2023 at 19:10
  • It's fine if it shows the arguments Commented Mar 23, 2023 at 19:17
  • ps -ef | grep [w]ord is wrong. [w]ord is also a glob to the shell, so is expanded to matching files first. Had you used a saner shell like zsh, you'd have seen a no match error (assuming there's no file called word in the current working directory). ps -Af | grep '[w]ord' Commented Mar 23, 2023 at 19:20

3 Answers 3


Simply run:

pgrep -fl script.sh

From man pgrep:

pgrep, pkill, pidwait - look up, signal, or wait for processes based on name and other attributes
-f, --full
The pattern is normally only matched against the process name. When -f is set, the full command line is used.
-l, --list-name
List the process name as well as the process ID. (pgrep only.)


In shells that support it, you could use the substring expansion to put the brackets in the right places:

ps -ef | grep "[${name:0:1}]${name:1}"

would run grep "[f]fmpeg" on the right hand side of the pipeline.

(That should be relatively safe with most special characters, since they're usually not special within brackets, but don't expect you'd have anything but letters there.)

Though pgrep is better in that it knows to ignore itself automatically. It just doesn't print everything ps does, but something like this might help with that:

ps -f -p $(pgrep "$name" |tr '\n' ',')

Would inverted-match with grep work?

grep -v 'grep\|script'

This will not match grep or script.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .