简体   繁体   中英

How to execute a local bash script on remote server via ssh with nohup

I can run a local script on a remote server using the -s option, like so:

# run a local script without nohup...
ssh $SSH_USER@$SSH_HOST "bash -s" < myLocalScript.sh;

And I can run a remote script using nohup , like so:

# run a script on server with nohup...
ssh $SSH_USER@$SSH_HOST "nohup bash myRemoteScript.sh > results.out 2>&1 &"

But can I run my local script with nohup on the remote server? I expect the script to take many hours to complete so I need something like nohup . I know I can copy the script to the server and execute it but then I have to make sure I delete it once the script is complete, would rather not have to do that if possible.

I've tried the following but it's not working:

# run a local script without nohup...
ssh $SSH_USER@$SSH_HOST "nohup bash -s > results.out 2>&1 &" < myLocalScript.sh; 

You shouldn't have to do anything special - Once you kick off a script on another machine, it should finish running even if you terminate the connection:

For example

ssh $SSH_USER@$SSH_HOST "bash -s > results.out 2>&1" < myLocalScript.sh &

# Please wait a few seconds for the connection to be established
kill $! # Optional: Kill the last process

If you want to test it, try a simple script like this

# myLocalScript.sh
echo 'File created - sleeping'
sleep 30
echo 'Finally done!'

The results.out file should immediately be created on the other machine with "File created - sleeping" in it. You can actually kill the local ssh process with kill <your_pid> , and it will still keep running on the other machine, and after 30 seconds, print "Finally done!" into the file, and exit.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM