I know you can suspend a ssh session with ~^z, but is there also a way to background it so that it continues working while you do something else in the local shell?
If you're trying to run a process remotely, and you don't care about keeping the ssh session open, you may want to look at using
screen. It will allow you to run your process in the "background", and it will keep running after you logout.
ssh over to the remote box, then from there use
screen and start your process, and you can give your
screen a session name if you want. You won't really notice anything different, but start your process in that session. You can than exit out of the
screen session by using the command
Ctrl-a d. It will look something like this:
user@remotebox:~$ screen -S foobarsession user@remotebox:~$ startmyprocess [detached from 4865.foobarsession] user@remotebox:~$
You can then exit out of your ssh session, and the process will keep running. To reconnect to the
screen session later on, ssh back to the remote box and use
screen -r to reconnect. You can use
screen -ls to list the sessions.
user@remotebox:~$ screen -ls There is a screen on: 4865.foobarsession (10/05/2012 11:10:57 AM) (Detached) 1 Socket in /var/run/screen/S-user user@remotebox:~$ screen -r foobarsession user@remotebox:~$ screen -ls 4865.foobarsession (10/05/2012 11:10:57 AM) (Attached) 1 Socket in /var/run/screen/S-user user@remotebox:~$
screen isn't installed, you could use the
nohup command on the remote box. Wikipedia explains that well:
Nohupping backgrounded jobs is typically used to avoid terminating them when logging off from a remote SSH session. A different issue that often arises in this situation is that ssh is refusing to log off ("hangs"), since it refuses to lose any data from/to the background job(s). This problem can also be overcome by redirecting all three I/O streams: nohup ./myprogram > foo.out 2> foo.err < /dev/null &
So you could do something like:
ssh -n -f user@remotebox "sh -c 'cd /foo/bar; nohup ./myprogram > foo.out 2> foo.err < /dev/null &'"
After ~^z execute
bg and the stopped process will continue to execute in background. Works with all processes not just ssh.
fg you foreground the backgrounded process again. And just for the record: The ~ is only needed to distinguish whether the suspension should be on the local machine (with ~ --> the ssh client) or on the server (without ~ --> whatever process is currently running in foreground on the server)