Search code examples
javalinuxbashsshconnection

Run bash file on remote linux machine with java and keep it in background


I have a shell script on a remote linux machine which contains the following:

#!/bin/sh
for i in $(seq 1 10);
do
   echo "CREATE TABLE ben$i (id NUMBER NOT NULL);
   ! sleep 30
   select * from ben$i;
   ! sleep 30
   DROP TABLE ben$i;" | sqlplus system/password &
done
wait

The name of this script is ben.sh.

In java, i want to execute this script and keep the script doing what it does in background.

I have a command that execute the script successfully:

sshshell.execute("su - oracle -c './ben.sh'");

I want the script to still run on the remote linux machine and i want to close the ssh connection right after i execute the command above, without interfering the script.

I thought if i put an & at the end of this command like so:

sshshell.execute("su - oracle -c './ben.sh' &");

But still the java program stuck and waits for the script to finish

Very important note: I don't want to use Threads OR any additional ssh connections.

What are my options here?


Solution

  • Use nohup and & to run the script in the background.

    sshshell.execute("nohup su - oracle -c './ben.sh' &");
    

    Nohup is short for “No Hangups". Nohup is a supplemental command that tells the Linux system not to stop another command once it has started. That means it’ll keep running until it’s done, even if the user that started it logs out. The syntax for nohup is as follows:

    nohup sh your-script.sh &
    

    The & at the end moves the command to the background, freeing up the terminal that you’re working in.