hyde
hyde

Reputation: 62787

Nicer one-liner for exiting bash script with error message

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.

Upvotes: 9

Views: 6456

Answers (1)

devnull
devnull

Reputation: 123458

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.

Upvotes: 23

Related Questions