Example output
$ ./undefined_vs_empty.bash
x was not set.
$ ./undefined_vs_empty.bash -x ''
x was set to: ''
$ ./undefined_vs_empty.bash -x hello
x was set to: 'hello'| #! /usr/bin/env bash | |
| # try it: | |
| # $ ./undefined_vs_empty.bash | |
| # $ ./undefined_vs_empty.bash -x '' | |
| # $ ./undefined_vs_empty.bash -x hello | |
| parse_cli() { | |
| local OPTARG OPTIND | |
| local x | |
| while getopts ':x:' opt "$@"; do | |
| case "$opt" in | |
| x) | |
| x="$OPTARG" | |
| ;; | |
| esac | |
| done | |
| shift "$(( OPTIND - 1 ))" | |
| if [[ "${x+defined}" = 'defined' ]]; then | |
| # if $x is defined, ${x+defined} will substitute in 'defined' | |
| # this will take empty strings into account and treat them as defined. | |
| echo "x was set to: '$x'" | |
| else | |
| # $x is undefined | |
| echo "x was not set." | |
| fi | |
| } | |
| parse_cli "$@" |