Bash, no-arguments warning, and case decisions

If only interested in bailing if a particular argument is missing, Parameter Substitution is great:

#!/bin/bash
# usage-message.sh

: ${1?"Usage: $0 ARGUMENT"}
#  Script exits here if command-line parameter absent,
#+ with following error message.
#    usage-message.sh: 1: Usage: usage-message.sh ARGUMENT

Example

 if [ -z "$*" ]; then echo "No args"; fi

Result

No args

Details

-z is the unary operator for length of string is zero. $* is all arguments. The quotes are for safety and encapsulating multiple arguments if present.

Use man bash and search (/ key) for "unary" for more operators like this.


if [[ $# -eq 0 ]] ; then
    echo 'some message'
    exit 0
fi

case "$1" in
    1) echo 'you gave 1' ;;
    *) echo 'you gave something else' ;;
esac

The Advanced Bash-Scripting Guide is pretty good. In spite of its name, it does treat the basics.

Tags:

Bash