Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

` marks in script are messing things up 1

Status
Not open for further replies.

cpjust

Programmer
Sep 23, 2003
2,132
US
OK, I've got the following script:

Code:
#!/bin/bash

EXEC_NAME=$1

echo "$EXEC_NAME" | grep "/" > /dev/null 2>&1

if [ "$?" -eq "0" ]; then
        EXEC=`echo "$EXEC_NAME" | sed "s:\(.\)\(.*\):\2:"`
  echo "EXEC = $EXEC"
       PID=`pgrep -f $EXEC`
else
        PID=`pgrep -x $EXEC_NAME`
fi

echo "PID = $PID"

and if I do a 'ps -ef' I only have 1 process with '/usr/sbin/cron', so I run my script:
Code:
./check.sh "/usr/sbin/cron"
and it returns 2 PID's.
If I run the same thing myself:
Code:
pgrep -f "/usr/sbin/cron"
I only get 1 PID.
I'm pretty sure something is getting screwed up in the line with the ` characters:
Code:
PID=`pgrep -f $EXEC`
How can I fix it to only return a single PID?
 
While you are running this script, there is a process running called ./check.sh /usr/sbin/cron. pgrep is finding this process as well, hence the second PID.

When you run [p]pgrep -f /usr/sbin/cron[/b] on its own, it knows that it should ignore itself in the process listing. One trick to avoid this is to use something like pgrep -f [/]usr/sbin/cron. The extra square brackets have no impact on the regular expression, but they do prevent it from being matched in the process list.

Incidentally, a simpler way to strip off the first character is sed 's/^.//'. Also you may want to match against "^/" in your grep so that it only matches slashes on the beginning of the string, if that's all you are intending to remove. In any case, I think the logic is flawed, because pgrep -x only seems to work for me (on Solaris 10 anyway) if you remove the entire pathname, i.e. just search for "cron".



Annihilannic.
 
Cool! That makes total sense, I don't know why I didn't think of it...
I even found a much easier way to do it:
Code:
#!/bin/bash

EXEC_NAME=$1

echo "$EXEC_NAME" | grep "/" > /dev/null 2>&1

if [ "$?" -eq "0" ]; then
        PID=`pgrep -f ^$EXEC_NAME`
else
        PID=`pgrep -x $EXEC_NAME`
fi

echo "PID = $PID"
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top