5 Ways to Execute UNIX / Linux Commands (and Shell Scripts) in Background
Question: I know how to execute a Unix command in the foreground. Can you please explain me how I can execute a Linux command in the background?
Answer: You can use one of the 5 methods explained in this article to execute a Linux command, or shell script in the background.
1. Execute a command in the background using &
You can execute a command (or shell script) as a background job by appending an ampersand to the command as shown below.
$ ./my-shell-script.sh &
Read Bg, Fg, &, Ctrl-Z – 5 Examples to Manage Unix Background Jobs to understand more details.
2. Execute a command in the background using nohup
After you execute a command (or shell script) in the background using &, if you logout from the session, the command will get killed. To avoid that, you should use nohup as shown below.
$ nohup ./my-shell-script.sh &
Read Unix Nohup: Run a Command or Shell-Script Even after You Logout to understand more details.
3. Execute a command using screen command
After you execute a command in the background using nohup and &, the command will get executed even after you logout. But, you cannot connect to the same session again to see exactly what is happening on the screen. To do that, you should use screen command.
Linux screen command offers the ability to detach a session that is running some process, and then attach it at a later time. When you reattach the session later, your terminals will be there exactly in the way you left them earlier.
Refer Screen Command Examples: Get Control of Linux / Unix Terminal to understand more details.
4. Executing a command as a batch job using at
Using at command you can schedule a job to run at a particular date and time. For example, to execute the backup script at 10 a.m tomorrow, do the following.
$ at -f backup.sh 10 am tomorrow
Read Understand at, atq, atrm, batch Commands using 9 Examples for more details.
Running certain jobs in batch mode requires certain options to be enabled. Following articles will give some clarity on those.
- How To Capture Unix Top Command Output to a File in Readable Format
- Unix bc Command Line Calculator in Batch Mode
- How To Execute SSH and SCP in Batch Mode (Only when Passwordless login is enabled)
5. Execute a command continuously using watch
To execute a command continuously at a certain interval, use watch command as shown below.
$ watch df -h
Read Watch: Repeat Unix Commands or Shell-Scripts every N seconds to understand more details.
Niciun comentariu:
Trimiteți un comentariu