0

I'm using Ubuntu 16.04 LTS and I try to grep the PID of some process. Here is what I've done in terminal:

# ps aux | grep xorg | grep -v 'grep' | awk '{print $2}'

After executing the command above, I get the result:

2367

However, then I create a script named t.sh as below:

#!/bin/bash
a=$(ps aux | grep $1 | grep -v 'grep' | awk '{print $2}')
echo $a

I execute it: ./t.sh xorg But I get: 2367 57270 57271

I have no idea where the two numbers come from. I only know that the two numbers always change when I execute ./t.sh xorg and they are adjacent (n and n + 1).

I just found another thing: If I fix xorg into the script, instead of passing parameter, the two numbers will disappear.

#!/bin/bash
a=$(ps aux | grep xorg | grep -v 'grep' | awk '{print $2}')
echo $a

This script will work as expected.

Duplicated question

Different results between ps aux and `ps aux` inside a script

After reading the post, I still don't know what I can do to solve my problem.

Community
  • 1
  • 1
Yves
  • 11,597
  • 17
  • 83
  • 180

0 Answers0