5

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' 'blah@foo.com' &
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?

vezult
  • 430

3 Answers3

4

The shell builtin you're looking for is disown, which re-parents backgrounded jobs to init 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.

ssh hostname 'command' &>/dev/null &
disown
Kyle Smith
  • 9,808
1

Isn't the wait causing your script to erm wait ? From the man page ...

wait [n ...] Wait for each specified process and return its termination status. Each n may be a process ID or a job specifi- cation; if a job spec is given, all processes in that job’s pipeline are waited for. If n is not given, all currently active child processes are waited for, and the return status is zero. If n specifies a non-existent process or job, the return status is 127. Otherwise, the return status is the exit status of the last process or job waited for.

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.

user9517
  • 117,122
0

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 the screen 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.