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.
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.
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.
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.
The || is an “or” comparison operator. The : is a null operator which does… Nothing. Well, it does return a successful exit status…
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With