Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting ssh to execute a command in the background on target machine

Tags:

bash

ssh

csh

This is a follow-on question to the How do you use ssh in a shell script? question. If I want to execute a command on the remote machine that runs in the background on that machine, how do I get the ssh command to return? When I try to just include the ampersand (&) at the end of the command it just hangs. The exact form of the command looks like this:

ssh user@target "cd /some/directory; program-to-execute &" 

Any ideas? One thing to note is that logins to the target machine always produce a text banner and I have SSH keys set up so no password is required.

like image 741
dagorym Avatar asked Aug 26 '08 22:08

dagorym


People also ask

How do I SSH in the background?

To execute SSH command remotely in the background without this issue, you need to prevent SSH from blocking for input by redirecting the output to /dev/null. You will then also need to send your SSH client session to the background. You can achieve both effects by using the -n and -f options for the SSH client.

How do you run a command in the background using SSH and detach the session?

ssh into your remote box. Type screen Then start the process you want. Press Ctrl - A then Ctrl - D . This will "detach" your screen session but leave your processes running.

How do I run a command in the background Shell?

Running shell command or script in background using nohup command. Another way you can run a command in the background is using the nohup command. The nohup command, short for no hang up, is a command that keeps a process running even after exiting the shell.

How do I run a command in the background in Linux?

Use bg to Send Running Commands to the Background You can easily send these commands to the background by hitting the Ctrl + Z keys and then using the bg command. Ctrl + Z stops the running process, and bg takes it to the background. You can view a list of all background tasks by typing jobs in the terminal.


1 Answers

I had this problem in a program I wrote a year ago -- turns out the answer is rather complicated. You'll need to use nohup as well as output redirection, as explained in the wikipedia artcle on nohup, copied here for your convenience.

Nohuping backgrounded jobs is for example useful when logged in via SSH, since backgrounded jobs can cause the shell to hang on logout due to a race condition [2]. This problem can also be overcome by redirecting all three I/O streams:

nohup myprogram > foo.out 2> foo.err < /dev/null & 
like image 147
Jax Avatar answered Nov 12 '22 19:11

Jax