Trap in bash

What’s the trap command

The trap command provides the script to captures an interrupt (signal) and then clean it up within the script.

trap [-lp] [arg] [sigspec …]

The commands in arg are to be read and executed when the shell receives signal sigspec. If arg is absent (and there is a single sigspec) or equal to ‘-’, each specified signal’s disposition is reset to the value it had when the shell was started. If arg is the null string, then the signal specified by each sigspec is ignored by the shell and commands it invokes. If arg is not present and -p has been supplied, the shell displays the trap commands associated with each sigspec. If no arguments are supplied, or only -p is given, trap prints the list of commands associated with each signal number in a form that may be reused as shell input. The -l option causes the shell to print a list of signal names and their corresponding numbers. Each sigspec is either a signal name or a signal number. Signal names are case insensitive and the SIG prefix is optional.

If a sigspec is 0 or EXIT, arg is executed when the shell exits. If a sigspec is DEBUG, the command arg is executed before every simple command, for command, case command, select command, every arithmetic for command, and before the first command executes in a shell function. Refer to the description of the extdebug option to the shopt builtin (see The Shopt Builtin) for details of its effect on the DEBUG trap. If a sigspec is RETURN, the command arg is executed each time a shell function or a script executed with the . or source builtins finishes executing.

If a sigspec is ERR, the command arg is executed whenever a pipeline (which may consist of a single simple command), a list, or a compound command returns a non-zero exit status, subject to the following conditions. The ERR trap is not executed if the failed command is part of the command list immediately following an until or while keyword, part of the test following the if or elif reserved words, part of a command executed in a && or || list except the command following the final && or ||, any command in a pipeline but the last, or if the command’s return status is being inverted using !. These are the same conditions obeyed by the errexit (-e) option.

Signals ignored upon entry to the shell cannot be trapped or reset. Trapped signals that are not being ignored are reset to their original values in a subshell or subshell environment when one is created.

The return status is zero unless a sigspec does not specify a valid signal.

Common signals

SignalDescription
EXIT(Bash Builtin) Triggered When the script is normal exit or set -e exit with the error
ERR(Bash Builtin) see above trap usage
DEBUG(Bash Builtin) we instead of “set -x && export PS4=’+[${FUNCNAME[0]}:$LINENO]”
INTTriggered by Ctrl + C
TERMTerminate - Trigger by kill command

When and How to trap

When receiving a signal, actions that can take place are:
- cleaning up files
- ignoring the actual signal
- carry on processing

1 trap used to cleaning up files

#!/bin/env bash

# Enalbe errexit (-e) option
set -e

# Defines a working area on the file system.
swap_path=/tmp/SWAP_$$

clean_up() {
 [ -f "$swap_path" ] && rm -f $swap_path
}

trap clean_up EXIT INT TERM
mkdir -p "$swap_path"

# All temp files created under $swap_path.

# If executed successfully, reset trap.
trap - EXIT INT TERM
clean_up

2 trap for error handling

#!/bin/env bash

ERRTRAP() {
  echo "[$1] Error: Error exited with status $?"
}

func() {
  # not root user do this will raise permission denied.
  cat /etc/shadow
}

trap 'ERRTRAP $LINENO' ERR
func

3 trap for ignoring signal

#!/bin/env bash

# not allow to Ctrl+C to terminate process. 
# trap and do nothing.
trap ''  INT 

Reference

  1. Using traps in your scripts
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值