0
# echo ${var}

# echo ${var:-world}
world
# var='hello'
# echo ${var}
hello
# echo ${var:-world}
hello

Could you explain why the second echo ${var:-world} output hello other than world?

By the way, what's the topic called in English? I searched cut string, sub string... Thanks.

caisil
  • 363
  • 2
  • 14
  • 1
    Are you doing these experiments as root? Or are you using '# ' as the default prompt for a non-root user? Either way, stop doing that. – William Pursell Apr 28 '17 at 13:41
  • @WilliamPursell Yes, I login as root. Why can not using "#"? Is it stackoverflow rule, or some other concerns for using linux? – caisil Apr 29 '17 at 03:29
  • The convention is that '#' as the leading character in the prompt indicates a root login. it is nearly universally acknowledged that running an interactive shell as root is bad practice, and since the introduction of `sudo` rarely necessary. – William Pursell Apr 29 '17 at 15:15
  • @WilliamPursell Yeah, universal but for me :). Anyway, thanks! I'll try to be more professional. – caisil Apr 30 '17 at 01:42

1 Answers1

0

${name:-alternate} is a parameter expansion with a default value. From the man page:

${parameter:-word}

Use Default Values. If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.

The first ${var:-world} printed world because $var was unset. The second printed hello because you had set $var=hello, so $var was no longer unset. Therefore, the default (world) was ignored.

More info is at the bash-hackers wiki.

Community
  • 1
  • 1
cxw
  • 16,685
  • 2
  • 45
  • 81