Skip to content

Instantly share code, notes, and snippets.

@nima
Created March 28, 2017 23:21
Show Gist options
  • Save nima/f27539056be0b4600c205bb563f4a911 to your computer and use it in GitHub Desktop.
Save nima/f27539056be0b4600c205bb563f4a911 to your computer and use it in GitHub Desktop.
How the various bash operators work
#!/bin/bash
cat <<!
+--------------+-----------------+-----------------+-----------------+
| | var | var | var |
| Statement | SetNotNull | SetButNull | Unset |
+--------------+-----------------+-----------------+-----------------+
| \${var:-word} | substitute var | substitute word | substitute word |
| \${var-word} | substitute var | substitute null | substitute word |
| \${var:=word} | substitute var | assign word | assign word |
| \${var=word} | substitute var | substitute null | assign word |
| \${var:+word} | substitute word | substitute null | substitute null |
| \${var+word} | substitute word | substitute word | substitute null |
| \${var:?word} | substitute var | error, exit | error, exit |
| \${var?word} | substitute var | substitute null | error, exit |
+--------------+-----------------+-----------------+-----------------+
!
set +u
{
printf '@ Statement @ SetNotNull/Assigned @ SetButNull/Assigned @ Unset/Assigned @\n'
for op in ':-' '-' ':=' '=' ':+' '+' ':?' '?'; do
stmt="\${var${op}word}"
printf "@ %s" "${stmt}"
var='data'
printf ' @ '
( eval printf -- "%s/" "${stmt}" 2>/dev/null; printf "%s" ${var}) || printf "ERR"
var=''
printf ' @ '
( eval printf -- "%s/" "${stmt}" 2>/dev/null; printf "%s" ${var}) || printf "ERR"
unset var
printf ' @ '
( eval printf -- "%s/" "${stmt}" 2>/dev/null; printf "%s" ${var}) || printf "ERR"
echo ' @'
done
} | column -n -s@ -t
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment