Skip to content

Instantly share code, notes, and snippets.

@spikegrobstein
Created March 5, 2021 23:39
Show Gist options
  • Save spikegrobstein/ad79da7d8858b1af468e170c093d1ebd to your computer and use it in GitHub Desktop.
Save spikegrobstein/ad79da7d8858b1af468e170c093d1ebd to your computer and use it in GitHub Desktop.
proof that bash can differentiate between undefined and an empty string

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 "$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment