Job Control to Background And Foreground Command In Bash

Appending an & (ampersand) to any command run within bash will
background the process.

for count in $(seq 1 10); do
    sleep 10m &
[1] 17
[2] 18
[3] 19
[4] 20
[5] 21
[6] 22
[7] 23
[8] 24
[9] 25
[10] 26

Will background 10 processes which will simply sleep for 10 minutes. Bash will return a table of job ids and their PIDs.

To list a table which shows all background processes use the built-in
jobs command.

$ jobs -l
job management, bash job control, bash background worker, iş yönetimiPin

You can also use ps to list the background processes by requesting the
processes which have the parent pid of your current bash shell.

$ ps -O user --ppid $$
bash job management, bash ile iş yönetmi, arka planda iş çalıştırmaPin

By using ps we can refer to important information on the processes.

To connect to one of the background processes, use fg and the job id

fg 5
job management, bash job control, bash background worker, iş yönetimiPin

To put job 5 back into the background you first have to suspend the
process by using ^Z (Control-Z) and then running bg specifying the job

$ fg 5
sleep 10m
[11]+  Stopped                 sleep 10m
$ bg 5
[11]+ sleep 10m &

To put fg, bg and ^Z to practical use, lets say you were copying a large
directory which was going to take a long time though you wanted to
regain control of your current shell.

Suspend the current command using ^Z.

$ cp -a /opt/backups/files/hourly.0 /opt/restore
[1]+  Stopped                 cp -a /opt/backups/files/hourly.0 /opt/restore

Background the task with bg referring to the job id in the table.

$ bg 5
[1]+ cp -a /opt/backups/files/hourly.0 /opt/restore &

Confirm the process is running with ps.

$ ps -O user --ppid $$
45 mertcan     D tty1   00:00:16 cp -a /opt/backups/files/hourly.0 /opt/restore

Sistem Uzmanı, Linux Hacısı, El-Kernel

Yorum yapın