quangkeu95
11/7/2017 - 2:02 AM

Shell script knowledge about trap command

Shell script knowledge about trap command

Khi shell script nhận được một Signal, script có thể thực hiện một trong ba actions:

  1. Ignore and do nothing.
  2. Catch signal by using trap and do something.
  3. Take the default action.

Các actions trên đúng ngoại trừ trường hợp 3 signals:

  • SIGKILL (9)
  • SIGSTOP (17)
  • SIGCONT (19)

3 signals đặc biệt này không thể caught và sẽ thực hiện default action.

Trap command syntax

trap [COMMAND_LISTS] [SIGNALS]

  • COMMAND LISTS: list các actions hoặc là một function được run khi script received signals
  • SIGNALS: list các signals.

To ignore a signal

trap '' [SIGNALS]

Example:

#!/bin/bash

trap 'my_exit; exit' SIGINT SIGQUIT
count=0
 
my_exit()
{
echo "you hit Ctrl-C/Ctrl-\, now exiting.."
 # cleanp commands here if any
}
 
while :
 do
   sleep 1
   count=$(expr $count + 1)
   echo $count
 done