Shell补充之后台执行脚本程序

在实际工作中,一般会通过客户端SSH连接服务器,因此可能就会有在脚本或命令执行期间不能中断的需求,若中断,则会前功尽弃,更可能会破坏系统数据。为了预防因为ssh链接窗口的关闭而导致脚本运行中断,我们可以把脚本放在后台运行。

案例说明:

脚本信息

[root@node1 scripts]# cat while1.sh 
#! /bin/bash
while true 
do
  uptime >> /tmp/uptime.log
  sleep 2
done

把脚本放入后台运行

[root@node1 scripts]# bash while1.sh &
[1] 23277
[root@node1 scripts]# jobs
[1]+  Running                 bash while1.sh &
[root@node1 scripts]# 

把后台脚本转到前台执行

[root@node1 scripts]# jobs
[1]+  Running                 bash while1.sh &   #后台脚本运行时的jobs编号
[root@node1 scripts]# fg 1   #fg加jobs相应脚本或程序的编号,可以把相应的脚本或程序转到前台运行
bash while1.sh

杀掉在前台运行的脚本或程序

 
[root@node1 scripts]# jobs
[1]+  Running                 bash while1.sh &
[root@node1 scripts]# fg 1
bash while1.sh
#ctrl+c杀掉在前台运行的脚本或程序

kill命令关闭jobs任务脚本

[root@node1 scripts]# bash while1.sh &
[1] 23720
[root@node1 scripts]# bash while1.sh &
[2] 23723
[root@node1 scripts]# bash while1.sh &
[3] 23727
[root@node1 scripts]# jobs
[1]   Running                 bash while1.sh &
[2]-  Running                 bash while1.sh &
[3]+  Running                 bash while1.sh &

杀掉jobs中的第二个脚本
[root@node1 scripts]# jobs
[1]   Running                 bash while1.sh &
[2]-  Running                 bash while1.sh &
[3]+  Running                 bash while1.sh &
[root@node1 scripts]# kill %2
[root@node1 scripts]# jobs
[1]   Running                 bash while1.sh &
[2]-  Terminated              bash while1.sh     #jobs中第2个运行的脚本已经被杀掉
[3]+  Running                 bash while1.sh &

 

posted @ 2020-10-12 21:07  yaowx  阅读(601)  评论(0编辑  收藏  举报