Shell: What is the purpose of $ {var: -} when var is not specified or null?

In my Linux Mint 17.2,/etc/bash.bashrc I see the following:

# set variable identifying the chroot you work in (used in the prompt below)
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
    debian_chroot=$(cat /etc/debian_chroot)
fi

This is the first token reference debian_chroot.

Why does this code use ${debian_chroot:-}instead of just $debian_chroot?

Bash Shell parameter extension says:

$ {option: -word}

If the parameter is not specified or is null, the word is replaced. Otherwise, the parameter value will be replaced.

Here the word "null" is null, so why bother with replacing zero with null?

+4
source share
3 answers

${debian_chroot:-} , set -u ( undefined) debian_chroot .

, set -u ( ), .

:

bash -c 'set -u; [ -z $a ]; echo ok'          # error
bash -c 'set -u; a=; [ -z $a ]; echo ok'      # ok
bash -c 'set -u; [ -z ${a:-} ]; echo ok'      # ok
bash -c 'set -u; a=; [ -z ${a:-} ]; echo ok'  # ok
+3

"${variable:-}" script , - -u set -u - undefined.

-u , '@' *, . , .

+1

, , bash .

, var , :

if [ $var = "" ] #breaks => bash: [: =: unary operator expected

 if [ "${var:-}" = "" ] # works fine

if [ -z "${debian_chroot:-}" ] # z checks if a SET variable is empty.

, "${debian_chroot}" , -u bash .

[ bash ] :

-u (nounset) undefined

script

#!/bin/bash -u
# note variable 'var' is unset
# Try the script as is and uncommenting the below line
#declare var=
if [ -z "${var}" ]
then
 echo "var is empty"
fi
# "${var:-}" would work even if the 'var' is not 'declare'd.

.

-1

Source: https://habr.com/ru/post/1650989/


All Articles