#!/bin/bash# test trap commandtrap "echo 'Sorry! I have trapped Ctrl-C'" SIGINTecho This is a test scriptcount=1while [ $count -le 10 ]do echo "Loop $count" sleep 1 count=$[ $count + 1 ]doneecho The end.
运行结果:
This is a test scriptLoop 1Loop 2^CSorry! I have trapped Ctrl-CLoop 3Loop 4^CSorry! I have trapped Ctrl-CLoop 5Loop 6Loop 7Loop 8^CSorry! I have trapped Ctrl-CLoop 9Loop 10The end.
#!/bin/bash# test trap commandtrap "echo Goodbye." EXITecho This is a test scriptcount=1while [ $count -le 10 ]do echo "Loop $count" sleep 1 count=$[ $count + 1 ]doneecho The end.
运行结果:
This is a test scriptLoop 1Loop 2Loop 3Loop 4Loop 5Loop 6Loop 7Loop 8Loop 9Loop 10The end.Goodbye.
demo3——修改trap操作
#!/bin/bash# test trap commandtrap "echo 'Sorry! I have trapped Ctrl-C'" SIGINTcount=1while [ $count -le 5 ]do echo "Loop $count" sleep 1 count=$[ $count + 1 ]donetrap "echo 'Sorry! The trap has been modified.'" SIGINTcount=1while [ $count -le 5 ]do echo "Loop $count" sleep 1 count=$[ $count + 1 ]doneecho The end.
运行结果:
Loop 1Loop 2Loop 3^CSorry! I have trapped Ctrl-CLoop 4Loop 5Loop 1Loop 2Loop 3^CSorry! The trap has been modified.Loop 4Loop 5The end.