Issue
I have a shell snippet:
nohup sudo node server.js >> node.log 2>&1 &
if [ $? -eq 0 ]; then
echo $! $?
echo $! > pids
fi
What I expect is if the node server.js
run normaly, then record the pid of this process to the file: pids.
But it does'nt work, the $?
is always 0 because it is the status of sudo process?
And the $!
is also not the pid of the process of node
command.
So how can I get the correct return code and pid of the node server.js
in the above shell script?
Solution
My final solutions:
#!/usr/bin/env bash
ROOT=$(cd `dirname $0`; pwd)
sudo kill -9 `cat ${ROOT}/pids` || true
nohup sudo node server.js >> node.log 2>&1 &
sleep 1
pid=$(ps --ppid $! | tail -1 | awk '{ print $1 }')
if echo $pid | egrep -q '^[0-9]+$'; then
echo $pid > ${ROOT}/pids
else
echo 'server not started!'
fi
Answered By - atupal Answer Checked By - Candace Johnson (WPSolving Volunteer)