I'm trying to learn how to use getopts so that i can have scripts with parsed input although i think getopts could be better I am trying to just write a simple script to return partition usage percentages. The problem is that one of my bash functions does not seem to like that I reference $1 as an variable within the function. The reason I reference $1 is because the get_percent function can be passed a mount point as an optional argument to display instead of all of the mount points.

The script


set -e
set -u
set -o pipefail

    if [ -n "$1" ]
        df -h $1 | tail -n +2 | awk '{ print $1,"\t",$5 }'
        df -h | tail -n +2 | awk '{ print $1,"\t",$5 }'

    echo "script usage: $(basename $0) [-h] [-p] [-m mount_point]" >&2

# If the user doesn't supply any arguments, we run the script as normal
if [ $# -eq 0 ];
    exit 0
# ...

The Output

$ bash thing.sh
thing.sh: line 8: $1: unbound variable

$ bash -x thing.sh
+ set -e
+ set -u
+ set -o pipefail
+ '[' 0 -eq 0 ']'
+ get_percent
thing.sh: line 8: $1: unbound variable
Best Answer

set -u will abort exactly as you describe if you reference a variable which has not been set. You are invoking your script with no arguments, so get_percent is being invoked with no arguments, causing $1 to be unset.

Either check for this before invoking your function, or use default expansions ( ${1-default} will expand to default if not already set to something else).