简体   繁体   中英

Regarding PID Shell Script

I am calling another shell script testarg.sh within my main script. the logfiles of testarg.sh are stored in $CUSTLOGS in the below format

testarg.DDMONYY.PID.log example: testarg.09Jun10.21165.log

In the main script after the testarg process gets completed i need to grep the log file for the text "ERROR" and "COMPLETED SUCCESSFULLY". How do i get the PID of the process and combine with DDMONYY for grepping. Also i need to check whether file exists before grepping

$CUSTBIN/testarg.sh

$CUSTBIN/testarg.sh
rc=$?
if [ $rc -ne 0 ]; then
          return $CODE_WARN
fi

You may background testarg.sh , which puts its pid into $! , and then wait for it:

#! /bin/bash
...

$CUSTBIN/testarg.sh &

LOGFILE=testarg.$(date +%d%b%y).$!.log       # testarg.09Jun10.12345.log

wait $!

# ... $? is set as you expect ...

[ -f $LOGFILE ] && grep {pattern} $LOGFILE

...

If you can modify testarg.sh and it doesn't otherwise output anything, just change it to output its log file with a line like:

echo testarg.$(date +%blah).$$.log

then use:

fspec=$($CUSTBIN/testarg.sh)

in your parent.


Alternatively, you can provide a wrapper function to do the work:

#!/bin/bash
function fgpid() {
        "$@" &
        pid=$!
        ps -ef | grep ${pid} | sed 's/^/DEBUG:/' >&2 # debugging
        wait ${pid}
        echo ${pid}
}
fspec=testarg.$(date +%d%b%y).$(fgpid sleep 5).log
echo ${fspec}

This produces:

pax> ./qq.sh
DEBUG:pax    2656    2992 con  15:27:00 /usr/bin/sleep
testarg.09Jun10.2656.log

as expected.


Or this if you think your executable may output something. This one stores the PID into a variable:

#!/bin/bash
function fgpid() {
        "$@" &
        pid=$!
        ps -ef | grep ${pid} | sed 's/^/DEBUG:/' >&2 # debugging
        wait ${pid}
}
fgpid sleep 5
fspec=testarg.$(date +%d%b%y).${pid}.log
echo ${fspec}

There are two simple ways to get the PID of some process you've just spawned.

One would be to modify the program being spawned (the subprocess) to have it write its PID to a file. You'd then read it therefrom with something like:

 $CUSTBIN/testarg.sh
 TSTARGSPID=$(cat /var/run/custbin.testarg.pid)

Another more elegant method would be:

 $CUSTBIN/testarg.sh &
 TSTARGSPID=$!
 wait
 # Do stuff with PID and output files

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM