3

I'm reading a shell script for adding a progress bar to certain processes (found here). I'm having trouble understanding this (optional) line:

#BAR_EXT=${BAR_EXT-}

The comment says that this will add an extension to each file, and maybe I just need to read further, but I'm not familiar with that use of the - operator.

I know about this kind of substitution, as found in the Bash Reference Manual:

${parameter:-word}

I also know that the above will replace a null value for parameter with word, whereas ${parameter-word} will not. (At least, I think I know that.)

But with nothing specified after the - here, I'm not sure what's going on. Will this simply replace parameter with a null value? Generally, I would accept that as a working guess and just keep reading, but with the comment mentioning adding extensions to files.

1
  • 1
    With the # it's just a comment and ineffective. To understand the intention (once the hash symbol is removed) one would have to see the program. And, yes, you found the correct reference in the bash manual.
    – Janis
    Commented Mar 22, 2015 at 21:36

3 Answers 3

4

Does the script contain the command set -u?  That means

Treat unset variables and parameters other than the special parameters "@" and "*" as an error when performing parameter expansion.  If expansion is attempted on an unset variable or parameter, the shell prints an error message, and, if not interactive, exits with a non-zero status.

In other words, if $BAR_EXT is not set, something like

BAR_FILE="$BAR_FILE$BAR_EXT"

would fail.  The command

BAR_EXT=${BAR_EXT-}

will explicitly set $BAR_EXT to an empty string if it is not defined at all, thereby avoiding such an error.

1
  • Good, simple answer. I did a search in the script for set -u and nothing came up, but this does at least explain the effect of the trailing dash. Thanks!
    – wubzy
    Commented Mar 23, 2015 at 15:53
3

${VARIABLE-} expands to the value of VARIABLE if it's set, and to the empty string otherwise. This is usually what the straight $VARIABLE does. However, when the option set -u (set -o nounset) is on, $VARIABLE triggers an error when the variable is unset, whereas ${VARIABLE-} still produces an empty string. So ${VARIABLE-} means “I intended this to result in an empty string even if the variable is unset”, whereas $VARIABLE could mean that or could mean “I intended the variable to be set”.

1
  • Also a good answer. Rounds out my understanding of the above. Thanks!
    – wubzy
    Commented Mar 23, 2015 at 15:57
-3

Check the man page for the recent Bourne Shell:

http://schillix.sourceforge.net/man/man1/bosh.1.html

and look for the section "Parameter Substitution", this is currently on page 8. Two pages downwards, there is a table that explains all possible expansions.

The Bourne Shell supports much more than just '-' in parameter substitution.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .