简体   繁体   中英

How to return the PID from a bash script executed from a bash script

The get_pid() function below is intended to return the PID of daemon_itinerary.sh .

The script below is not in the same working directory as daemon_itinerary.sh .

#!/bin/bash

PID=""

get_pid() {
    PID='pidof daemon_itinerary.sh'
}

start() {
    echo "Restarting test_daemon"
    get_pid
    if [[ -z $PID ]]; then
        echo "starting test_daemon .."
        sh /var/www/bin/daemon_itinerary.sh &
        get_pid
        echo "done. PID=$PID"
    else
        echo "test_deamon is alrady running, PID=$PID"
    fi
}

case "$1" in
start)
    start
;;
...
*)
    echo "Usage: $0 {start|stop|restart|status}"
esac

*edit

Start is being passed in as a command line argument.

we use pgrep to get the pid of a processm like below

PID=$(pgrep -f "daemon_itinerary.sh" | xargs)

# xargs - is given because pgrep will return both process id as well as parent pid
# also it will help us to get all pids if multiple instances are running.
# pgrep option to get session id or parent id alone, here its from manual
# -P, --parent ppid,...
#     Only match processes whose parent process ID is listed.
# -s, --session sid,...
#     Only match processes whose process session ID is listed. Session ID 0 is translated into pgrep's or pkill's own session ID.

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