3

Is there a shell equivalent (in either bash or zsh) of Perl's die function?

I want to set the exit code and print a message in a single line. I know I can make my own simple function but I'm kind of hoping for a built in.

bahamat
  • 738
  • 2
  • 9
  • 19
  • 2
    possible duplicate of [In bash, is there an equivalent of die "error msg"](http://stackoverflow.com/questions/7868818/in-bash-is-there-an-equivalent-of-die-error-msg) – tripleee Dec 03 '12 at 20:38
  • Yep, this basically is a duplicate. I didn't find that when searching through though. – bahamat Dec 03 '12 at 22:26
  • Unfortunately, the search sucks. Try Google. – tripleee Dec 04 '12 at 05:59

2 Answers2

3

Nope, you need both echo and exit

glenn jackman
  • 238,783
  • 38
  • 220
  • 352
2

Just make a shell function like this :

die() {
    [[ $1 ]] || {
        printf >&2 -- 'Usage:\n\tdie <message> [return code]\n'
        [[ $- == *i* ]] && return 1 || exit 1
    }

    printf >&2 -- '%s' "$1"
    exit ${2:-1}
}

EXAMPLE

die "Oops, there's something wrong!\n" 255

EXPLANATIONS

  • the first argument is the needed message, the second optional argument is the return code :
  • ${2:-1} is a bash parameter expansion : it exit 1 if the second argument is missing
  • in , 1 is the same as FALSE (1 => 255)
  • in modern , die() { } is preferred as oldish function die {}
  • redirecting STDERR to STDOUT like Maxwell does, is not the best practice, instead, I redirect to STDERR directly (like perl does)
  • if you want to use it in interactive shell, put this in ~/.bashrc and then source ~/.bashrc
  • if you want to use it in scripts, you can source ~/.bashrc in your script or put it manually.
  • [[ $- == *i* ]] test whether you are in interactive shell or not
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223