English 中文(简体)
trapping shell exit code
原标题:

I am working on a shell script, and want to handle various exit codes that I might come across. To try things out, I am using this script:

#!/bin/sh
echo "Starting"
trap "echo "first one"; echo "second one"; " 1
exit 1;

I suppose I am missing something, but it seems I can t trap my own "exit 1". If I try to trap 0 everything works out:

#!/bin/sh
echo "Starting"
trap "echo "first one"; echo "second one"; " 0
exit

Is there anything I should know about trapping HUP (1) exit code?

最佳回答

trap dispatches on signals the process receives (e.g., from a kill), not on exit codes, with trap ... 0 being reserved for process ending. trap /blah/blah 0 will dispatch on either exit 0 or exit 1

问题回答

That s just an exit code, it doesn t mean HUP. So your trap ... 1 is looking for HUP, but the exit is just an exit.

In addition to the system signals which you can list by doing trap -l, you can use some special Bash sigspecs: ERR, EXIT, RETURN and DEBUG. In all cases, you should use the name of the signal rather than the number for readability.

You can also use || operator, with a || b, b gets executed when a failed

#!/bin/sh

failed
{
    echo "Failed $*"
    exit 1
}

dosomething arg1 || failed "some comments"




相关问题
KornShell- Creating a fixed width text file

I need to create a simple fixed width text file in KornShell (ksh). My current attempt using printf to pad the string isn t working out very well. What s the shortest, cleanest way to create a fixed ...

unix find command

how to use the find command to find files/directories which are not matching the pattern. for eg: find <some options > -name "dontfile.txt" should give me output of all the find whose file ...

encoding of file shell script

How can I check the file encoding in a shell script? I need to know if a file is encoded in utf-8 or iso-8859-1. Thanks

Case insensitive comparison of strings in shell script

The == operator is used to compare two strings in shell script. However, I want to compare two strings ignoring case, how can it be done? Is there any standard command for this?

1. 露台式照像

在Windows XP中,没有一时出现指挥时,是否有办法操作一种灰色文字? 我常常需要把“善待”(工作)与“灰色”同起来,即使我的文字没有产出,......

热门标签