Pages

Friday, March 3, 2017

TRAP Command

TRAP Command is used to read for a signals and to perform action. Main advantages of trap signal is, while running a shell script user may press (Ctrl + C) or (Ctrl +Z ) to break the process which may result in unwanted result. To avoid this we can use trap to capture the signal and perform the required action

Syntax : trap [-lp] [ARG] [SIGSPEC]

-l –> List all the signals and their numbers (Same output of Kill –l)

Test Cases:

FYI  - Signal 2 is for Ctrl +C and 20 is for Ctrl +Z

a) trap ‘ ’ 2 20 – if the argument is null, then signal specified by SIGSPEC is ignored by the shell

b) trap ‘echo Sig Rxed’ 2 20 – If the argument is present then whatever sigspec is received then it performs the mentioned action

c) trap ‘echo Failure’ ERR – If the SIGSPEC is ERR, the CMD arg is executed whenever simple command has a Non-Zero exit status

Note: - ERR Trap is not executed, if the failed command is a part of an Until/While/If Statement or part of a && (or) || list.

Eg: For ERR syntax

[xxxxxx@Test trap]$ cat trap.sh
#! /bin/bash
## Testing for trap
trap 'echo FAILURE' ERR
head -n 5 /etc/passwd
head -n 5 /etc/PASSWD

[xxxxxx@Test trap]$ sh trap.sh
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/adm:/sbin:/sbin/nologin
Ip:x:4:7:Ip:/var/spool/Ipd:/sbin/nologin
head: cannot open `/etc/PASSWD' for reading: No such file or directory
FAILURE

No comments:

Post a Comment