PDA

View Full Version : How to run linux command on background in bash(shell) script ?



Fli
04-18-2015, 10:52 AM
Hello, i just want to share this bash script code.



# definning emptybuffer function which will sleep 3600 seconds and empty buffer file when called.
# these commands (sleep, >) will be executed on background and script can continue to run
emptybuffer(){
sleep 3600
>/root/script/buffer
}

# if there is no "sleep 3600" process running, then we execute it (function emptybuffer)
if [ "$(ps x | grep "sleep 3600" | wc -l)" -lt "2" ];then
emptybuffer &
fi


Please if you know any other ways to simply execute linux command from bash script on background, please kindly share, thx

imort
06-03-2016, 01:54 PM
Hello, i just want to share this bash script code.
Please if you know any other ways to simply execute linux command from bash script on background, please kindly share, thx

You can just run the command like that:


./your_script.sh &

and it will be executed in the background return some result and finished.

RuskinF
08-05-2020, 01:29 PM
I have one more way of achieving this. Here are the steps:

If a process is already in execution, such as the tar command example below, simply press Ctrl+Z to stop it then enter the command bg to continue with its execution in the background as a job.

You can view all your background jobs by typing jobs. However, its stdin, stdout, stderr are still joined to the terminal.

$ tar -czf home.tar.gz .
$ bg
$ jobs
Run Linux Command in Background
Run Linux Command in Background

You can as well run a process directly from the background using the ampersand, & sign.

$ tar -czf home.tar.gz . &
$ jobs
Start Linux Process in Background
Start Linux Process in Background
Take a look at the example below, although the tar command was started as a background job, an error message was still sent to the terminal meaning the process is still connected to the controlling terminal.