Skip to content

Instantly share code, notes, and snippets.

@lambdalisue
Created October 13, 2022 04:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lambdalisue/d6aeb48312f7b068811dc09d60a1b21f to your computer and use it in GitHub Desktop.
Save lambdalisue/d6aeb48312f7b068811dc09d60a1b21f to your computer and use it in GitHub Desktop.
Bash test difference (-z/-n)
check() {
# -z: True when the string length is 0
if [ -z $DUMMY ]; then
echo '-z $DUMMY'
fi
if [ -z "$DUMMY" ]; then
echo '-z "$DUMMY"'
fi
if [ -z "${DUMMY+xxx}" ]; then
echo '-z "${DUMMY+xxx}"'
fi
if [ -z "${DUMMY:+xxx}" ]; then
echo '-z "${DUMMY:+xxx}"'
fi
# -n: True when the string length is greater than 0
if [ -n $DUMMY ]; then
echo '-n $DUMMY'
fi
if [ -n "$DUMMY" ]; then
echo '-n "$DUMMY"'
fi
if [ -n "${DUMMY+xxx}" ]; then
echo '-n "${DUMMY+xxx}"'
fi
if [ -n "${DUMMY:+xxx}" ]; then
echo '-n "${DUMMY:+xxx}"'
fi
}
echo
echo '# When $DUMMY is not defined'
unset DUMMY
check
echo
echo '# When $DUMMY is an empty string'
export DUMMY=""
check
echo
echo '# When $DUMMY is a non-empty string'
export DUMMY="foo"
check
@lambdalisue
Copy link
Author

# When $DUMMY is not defined
-z $DUMMY
-z "$DUMMY"
-z "${DUMMY+xxx}"
-z "${DUMMY:+xxx}"
-n $DUMMY

# When $DUMMY is an empty string
-z $DUMMY
-z "$DUMMY"
-z "${DUMMY:+xxx}"
-n $DUMMY
-n "${DUMMY+xxx}"

# When $DUMMY is a non-empty string
-n $DUMMY
-n "$DUMMY"
-n "${DUMMY+xxx}"
-n "${DUMMY:+xxx}"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment