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.
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.
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
${2:-1} is a bash parameter expansion : it exit 1 if the second argument is missing1 is the same as FALSE (1 => 255)die() { } is preferred as oldish function die {} perl does)~/.bashrc and then source ~/.bashrcsource ~/.bashrc in your script or put it manually.[[ $- == *i* ]] test whether you are in interactive shell or not