In bash, is there an equivalent die "error msg"

In perl, you can exit with an error message using die "some msg" . Is there an equivalent single command in bash? Right now I am achieving this with the commands: echo "some msg" && exit 1

+44
bash shell
Oct 23 2018-11-11T00:
source share
5 answers

You can easily collapse yourself:

 die() { echo "$*" 1>&2 ; exit 1; } ... die "Kaboom" 
+44
Oct. 23 2018-11-11T00:
source share

Here is what I use. It is too small to fit the library, so I had to type it hundreds of times ...

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

Usage: die 127 "Syntax error"

+17
Oct 23 2018-11-11T00:
source share

This is a very close function for perl "die" (but with a 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 the bash way to fade out if the build function failed (with the 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 stores all the necessary information in several environment variables:

  • LINENO - current line number of execution
  • FUNCNAME - stack of function calls, the first element (index 0) is the current function, the second (index 1) is the function that calls the current function
  • BASH_LINENO - call the stack of lines where the corresponding name FUNCNAME was called
  • BASH_SOURCE - an array of the source file in which the FUNCNAME match is stored
+9
Jan 17 '14 at 16:51
source share

Yes, that is pretty much how you do it.

You can use a semicolon or a new line instead of & &, since you want to get out of whether or not echo was successful (although I'm not sure what would happen).

Shell programming means using a large number of small commands (some built-in commands, some tiny programs) that do well and combine them with file redirection, code output logic, and other glue.

It may seem strange if you are used to languages ​​where everything is done using functions or methods, but you get used to it.

+1
Oct 23 '11 at 20:14
source share
 # 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 
0
May 11 '12 at 20:10
source share



All Articles