Skip to content

Instantly share code, notes, and snippets.

@quangkeu95
Last active November 7, 2017 02:23
Show Gist options
  • Save quangkeu95/6e8465b2880e14f40396dde4c716719a to your computer and use it in GitHub Desktop.
Save quangkeu95/6e8465b2880e14f40396dde4c716719a to your computer and use it in GitHub Desktop.
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment