How to run shell script in background

We need sometime run the script in background

1. How to execute the script in Background
Let us say you have created script call test_bg.sh

Login to remote host with appropricate username and password

Syntax
$ nohup <scriptname> > <logname> &
Example:
$ nohup /home/oracle/mudhalvan/scripts/test_bg.sh > /home/oracle/mudhalvan/scripts/test_bg.log &

2. How to check any background jobs are running in this session
$ jobs

3. Test with example
oracle@localhost:~/mudhalvan/scripts$ cat test_bg.sh

find /. -name “test” -print
oracle@localhost:~/mudhalvan/scripts$ ls -ltr test_bg.sh
-rwxr-xr-x 1 oracle oinstall 29 May 27 19:43 test_bg.sh
oracle@localhost:~/mudhalvan/scripts$
oracle@localhost:~/mudhalvan/scripts$ nohup /home/oracle/mudhalvan/scripts/test_bg.sh > /home/oracle/mudhalvan/scripts/test_bg.log &
[1] 3865
oracle@localhost:~/mudhalvan/scripts$ jobs
[1]+ Running nohup /home/oracle/mudhalvan/scripts/test_bg.sh > /home/oracle/mudhalvan/scripts/test_bg.log &
oracle@localhost:~/mudhalvan/scripts$

4. Why we need to run the scripts in background

1. You may be connected remotely to the server and execute some script which need to be executed for more than few hours. Due to network issue or session security you remote session may disconnect which may cause your running script end at half way.

2. Long running script which will not take your one session of your remote client connection from your client machine.

5. Benifits of running a script in background

1. Disconnect or network disturbance on your remote client will not impact your script execution
2. You can use the current remote session for another process

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.