PJx
PJx

Reputation: 1093

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

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

Upvotes: 93

Views: 61611

Answers (5)

Sergey Irisov
Sergey Irisov

Reputation: 508

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

Upvotes: 20

Keith Thompson
Keith Thompson

Reputation: 263257

You can roll your own easily enough:

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

Upvotes: 104

Yordan Georgiev
Yordan Georgiev

Reputation: 5430

# 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

Upvotes: 0

tripleee
tripleee

Reputation: 189387

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"

Upvotes: 35

bonkydog
bonkydog

Reputation: 2032

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.

Upvotes: 5

Related Questions