在 bash 中,是否存在与 die“ error msg”等价的

在 perl 中,可以使用 die "some msg"退出带有错误的 msg。Bash 中是否有一个等效的单一命令?现在,我使用命令 echo "some msg" && exit 1来实现这一点

52362 次浏览

Yep, that's pretty much how you do it.

You might use a semicolon or newline instead of &&, since you want to exit whether or not echo succeeds (though I'm not sure what would make it fail).

Programming in a shell means using lots of little commands (some built-in commands, some tiny programs) that do one thing well and connecting them with file redirection, exit code logic and other glue.

It may seem weird if you're used to languages where everything is done using functions or methods, but you get used to it.

You can roll your own easily enough:

die() { echo "$*" 1>&2 ; exit 1; }
...
die "Kaboom"

Here's what I'm using. It's too small to put in a library so I must have typed it hundreds of times ...

warn () {
echo "$0:" "$@" >&2
}
die () {
rc=$1
shift
warn "$@"
exit $rc
}

Usage: die 127 "Syntax error"

# echo pass params and print them to a log file
wlog(){
# check terminal if exists echo
test -t 1 && echo "`date +%Y.%m.%d-%H:%M:%S` [$$] $*"
# check LogFile and
test -z $LogFile || {
echo "`date +%Y.%m.%d-%H:%M:%S` [$$] $*" >> $LogFile
} #eof test
}
# eof function wlog




# exit with passed status and message
Exit(){
ExitStatus=0
case $1 in
[0-9]) ExitStatus="$1"; shift 1;;
esac
Msg="$*"
test "$ExitStatus" = "0" || Msg=" ERROR: $Msg : $@"
wlog " $Msg"
exit $ExitStatus
}
#eof function Exit

This is a very close function to perl's "die" (but with function name):

function die
{
local message=$1
[ -z "$message" ] && message="Died"
echo "$message at ${BASH_SOURCE[1]}:${FUNCNAME[1]} line ${BASH_LINENO[0]}." >&2
exit 1
}

And bash way of dying if built-in function is failed (with function name)

function die
{
local message=$1
[ -z "$message" ] && message="Died"
echo "${BASH_SOURCE[1]}: line ${BASH_LINENO[0]}: ${FUNCNAME[1]}: $message." >&2
exit 1
}

So, Bash is keeping all needed info in several environment variables:

  • LINENO - current executed line number
  • FUNCNAME - call stack of functions, first element (index 0) is current function, second (index 1) is function that called current function
  • BASH_LINENO - call stack of line numbers, where corresponding FUNCNAME was called
  • BASH_SOURCE - array of source file, where corresponfing FUNCNAME is stored