寫在前面:案例、常用、歸類、解釋說明。(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 -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信号:
# testing the script exit
trap "echo byebye" EXIT
while [ count -le 5 ] do echo "Loop #count -le 5 ] do echo "Loop #count"
sleep 3
結果:
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字樣)
移除捕獲
要移除捕獲,使用破折号作為指令和想要恢複正常行為的信号清單:
# testing the script
trap - EXIT
(信号捕獲移除後,腳本将忽略信号。但是,如果在移除捕獲之前收到信号,将繼續執行捕獲)
test1 &
(以背景模式運作)
在不使用控制台的情況下運作腳本
有時需要從終端會話啟動shell腳本,然後讓腳本在結束之前以背景模式運作,即使退出終端會話也是如此。
nohup指令,使用nohup指令時,關閉會話後腳本将忽略任何終端會話發送的SIGHUP信号。
作業控制
重新開機、停止、終止和恢複作業的操作稱為作業控制(job control)。使用作業控制可以完全控制程序在shell環境中運作的方式。
參看作業
# testing the script
echo "This is a test program $$"
while [ $count -le 10 ]
do
echo "Loop #$count"
count=$[ $count + 1 ]
運作中進行中斷和一系列操作
[root@localhost shellscript]# test1
This is a test program 30016
^Z
[1]+ Stopped test1
[root@localhost shellscript]# ./test1 >testout &
[2] 30026
[root@localhost shellscript]# jobs
[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指令不是安排腳本在預設的時間運作,而是安排腳本在系統使用率低時運作。
如果需要腳本在每天、每周或每月在同一時間運作,該怎麼辦呢?
本文轉自TBHacker部落格園部落格,原文連結:http://www.cnblogs.com/jiqing9006/p/3239941.html,如需轉載請自行聯系原作者