Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

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

like image 637
PJx Avatar asked Oct 23 '11 20:10

PJx


People also ask

What does [- Z $1 mean in bash?

$1 means an input argument and -z means non-defined or empty. You're testing whether an input argument to the script was defined when running the script. Follow this answer to receive notifications.

What does $@ mean in bash?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What is Dash E in bash?

by Aqsa Yasin. Set –e is used within the Bash to stop execution instantly as a query exits while having a non-zero status.

What does $# in bash mean?

$# is the number of positional parameters passed to the script, shell, or shell function. This is because, while a shell function is running, the positional parameters are temporarily replaced with the arguments to the function. This lets functions accept and use their own positional parameters.


2 Answers

You can roll your own easily enough:

die() { echo "$*" 1>&2 ; exit 1; } ... die "Kaboom" 
like image 172
Keith Thompson Avatar answered Sep 28 '22 03:09

Keith Thompson


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"

like image 36
tripleee Avatar answered Sep 28 '22 03:09

tripleee