Overview
- Using ‘&’ command
- Using ‘bg’ command
- Using ‘nohup’ utility
Using ‘&’ command
Use & at the last of the command to send the command in the background.
Syntax
command &
Example:
jhon-mbp:home jhon$ ping google.com > out 2>&1 &
[1] 17609
jhon-mbp:home jhon$ ping google.com &
[1] 18223
PING google.com (172.217.167.206): 56 data bytes
Note:– This is risky since it will throw output to the terminal and prevent you to type any command. so if a command sends out some output then redirect it to a file or somewhere or /dev/null before sending it to the background. That’s why I redirected the output of the command to a file name ‘out’ and appended ‘2>&1’ to redirect the error to the file as well along with output.
jobs command
It lists all the jobs running in the background with a job number written in placeholder []
jhon-mbp:home jhon$ jobs
[1]+ Running ping google.com > out 2>&1 &
fg command
Syntax:
fg %job_number
Note:- job_number you get after running the command using ‘&’ and can also find it in the outputs of the ‘jobs’ command.
Example:
jhon-mbp:home jhon$ fg %1
ping google.com > out 2>&1
^Cjhon-mbp:home jhon$
Note:- Once we bring the above command to the foreground then We had to cancel it using ‘Ctrl + C’ because it was blocking the terminal. So Always keep another terminal open in case something doesn’t work as planned you can kill that process using ‘kill’ or ‘pkill’ command from that terminal.
kill -9 $PID_NUMBER
pkill -9 -f "command name"
Using ‘bg’ command
To use this command follow these two steps.
- Run the command and press Ctrl + Z to stop it
- Now run the ‘bg’ command it will run the last command in the background
Example:
./git-p4.py clone --p4_spec p4-specs/file-spec.json --repo /root/code/myapp/testrepo -v --revisions @2020/09/09,now
Ctrl + Z #to Stop it
Now run the bg command
bg
Using ‘nohup’ utility
Just start the command with ‘nohup’ prefix. it detaches the terminal from the process and sends output and errors to its default log file i.e. nohup.out in the current directory. You can configure it to your own output file like the below commands
Example:
nohup ./git-p4.py clone --p4_spec p4-specs/file-spec.json --repo /root/code/myapp/testrepo -v --revisions @2020/09/09,now > results.out 2>&1 &
Note:-
- In the above command, we appended ‘&’ at last to free the terminal in the current session you can use the terminal and do other activities while the above long-running command will keep running.
- We redirected output/errors to a customized file. i.e. results.out using these lines in the above command “> results.out 2>&1“.
- We started the ‘workflow.py’ script with ‘nohup’ by writing before the command.