Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nicer one-liner for exiting bash script with error message

Tags:

bash

I'd like to achieve the test with a cleaner, less ugly one-liner:

#!/bin/bash
test -d "$1" || (echo "Argument 1: '$1' is not a directory" 1>&2 ; exit 1) || exit 1

# ... script continues if $1 is directory...

Basically I am after something which does not duplicate the exit, and preferably does not spawn a sub-shell (and as a result should also look less ugly), but still fits in one line.

like image 871
hyde Avatar asked Oct 22 '13 10:10

hyde


People also ask

How do you exit a bash script error?

Bash provides a command to exit a script if errors occur, the exit command. The argument N (exit status) can be passed to the exit command to indicate if a script is executed successfully (N = 0) or unsuccessfully (N != 0). If N is omitted the exit command takes the exit status of the last command executed.

What is exit 1 in bash script?

The exit status is an integer number. For the bash shell's purposes, a command which exits with a zero (0) exit status has succeeded. A non-zero (1-255) exit status indicates failure.

What is $@ in bash script?

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 does || mean in shell script?

The || is an “or” comparison operator. The : is a null operator which does… Nothing. Well, it does return a successful exit status…


1 Answers

Without a subshell and without duplicating exit:

test -d "$1" || { echo "Argument 1: '$1' is not a directory" 1>&2 ; exit 1; }

You may also want to refer to Grouping Commands:

{}

{ list; }

Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list is required.

like image 122
devnull Avatar answered Oct 05 '22 05:10

devnull