Linux&shell之如何控制脚本

写在前面:案例、常用、归类、解释说明。(By Jim)

Ctrl+C组合键可以生产SIGINT信号
Ctrl+Z组合键生产SIGTSTP信号,停止进程后程序仍然留在内存中,能够从停止的地方继续运行。

捕获信号

#!/bin/bash
# testing output in a background job

trap "echo Haha" SIGINT SIGTERM
echo "This is a test program"
count=1
while [ $count -le 10 ]
do
  echo "Loop #$count"
  sleep 10
  count=$[ $count + 1 ]
done
echo "This is the end of the test program"
(捕获到信息之后,就会输出一段文字Haha,脚本不会被终止)

捕获脚本退出
除了在shell脚本中捕获信号之外,还可以在shell脚本退出时捕获它们。
要捕获shell脚本退出,只需要向trap命令添加EXIT信号:
#!/bin/bash
# testing the script exit

trap "echo byebye" EXIT
echo "This is a test program"
count=1
while [ $count -le 5 ]
do
  echo "Loop #$count"
  sleep 3
  count=$[ $count + 1 ]
done
echo "This is the end of the test program"
结果:
This is a test program
Loop #1
Loop #2
Loop #3
Loop #4
Loop #5
This is the end of the test program
byebye
(在执行结束之后,捕获到,并输出byebye字样)

移除捕获
要移除捕获,使用破折号作为命令和想要恢复正常行为的信号列表:
#!/bin/bash
# testing the script

trap "echo byebye" EXIT
echo "This is a test program"
count=1
while [ $count -le 5 ]
do
  echo "Loop #$count"
  sleep 3
  count=$[ $count + 1 ]
done
trap - EXIT
echo "This is the end of the test program"
(信号捕获移除后,脚本将忽略信号。但是,如果在移除捕获之前收到信号,将继续执行捕获)

test1 &
(以后台模式运行)

在不使用控制台的情况下运行脚本
有时需要从终端会话启动shell脚本,然后让脚本在结束之前以后台模式运行,即使退出终端会话也是如此。
nohup命令,使用nohup命令时,关闭会话后脚本将忽略任何终端会话发送的SIGHUP信号。

作业控制
重启、停止、终止和恢复作业的操作称为作业控制(job control)。使用作业控制可以完全控制进程在shell环境中运行的方式。

参看作业
#!/bin/bash
# testing the script

echo "This is a test program $$"
count=1
while [ $count -le 10 ]
do
  echo "Loop #$count"
  sleep 10
  count=$[ $count + 1 ]
done
echo "This is the end of the test program"

运行中进行中断和一系列操作
[root@localhost shellscript]# test1
This is a test program 30016
Loop #1
Loop #2
Loop #3
Loop #4
^Z
[1]+  Stopped                 test1
[root@localhost shellscript]# ./test1 >testout &
[2] 30026
[root@localhost shellscript]# jobs
[1]+  Stopped                 test1
[2]-  Running                 ./test1 > testout &
(通过jobs指令进行捕获)

nice命令可以在启动命令时设置它的调度优先级。

准确无误地运行
at命令
batch命令
cron表格
at -f test1 16:22(test1脚本将与16:22运行)
列出排队的作业
at -f test1 5pm
atq(将列出排队的作业)
移除作业
atrm 8(移除作业8)

batch命令不是安排脚本在预设的时间运行,而是安排脚本在系统使用率低时运行。
如果需要脚本在每天、每周或每月在同一时间运行,该怎么办呢?

原文地址:https://www.cnblogs.com/jiqing9006/p/3239941.html