I'm attempting to create an ssh tunnel, spin it off into a background process, and write a pid file which I can later use to kill it. I CAN run ssh with -f
, but then I don't have a handle on its PID.
However, when I attempt to run the script below via nohup or setsid, control is never returned to the shell from which I attempt to daemonize the script.
#!/bin/sh
while getopts ":v" flag; do
case $flag in
v|verbose) verbose=1;;
:) echo "option -$lastflag requires an argument"; exit 1;;
esac
lastflag="$flag"
shift $((OPTIND - 1)); OPTIND=1
done
ssh -p '2222' -nNL '5984:localhost:5984' '[email protected]' &
pid=$!
sleep 2;
ps -p $pid >/dev/null 2>&1 || exit 1
echo $pid > "var/couchdb-tunnel.pid"
wait
Invocation:
nohup script.sh
setsid script.sh
How I do convince ssh (I assume) to let go of the terminal? Is there some other way I can accomplish what I want?
The shell builtin you're looking for is
disown
, which re-parents backgrounded jobs toinit
so that the script can exit leaving them safely in the background. You probably want to redirect output to/dev/null
(or a log file) in order to avoid getting output in the shell after starting the script.Isn't the
wait
causing your script to erm wait ? From the man page ...So your script is waiting for the ssh tunnel to complete before returning to the prompt. just remove the
wait
and you'll get a prompt back and your tunnel will be running in the background.I use
screen
to have different connections and scripts running in the same terminal window. This also allows me to shutdown my machine, go home, turn my machine back on and reload thescreen
session I wanted to keep tabs on what's going on.Of course this is assuming I'm SSH'd into another machine from my terminal.