Using More Than Just a Constant String for Default

Problem

You need something more than just a constant string as the default value for the variable.

Solution

You can use quite a bit more on the righthand side of these shell variable references. For example:

cd ${BASE:="$(pwd)"}

Discussion

As the example shows, the value that will be substituted doesn’t have to be just a string constant. Rather it can be the result of a more complex shell expression, including running commands in a subshell (as in the example). In our example, if $BASE is not set, the shell will run the pwd built-in command (to get the current directory) and use the string that it returns as the value.

So what can you do on the righthand side of this (and the other similar) operators? The bash manpage says that what we put to the right of the operator “is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.”

Here is what that means:

  • Parameter expansion means that we could use other shell variables in this expression, as in: ${BASE:=${HOME}}.

  • Tilde expansion means that we can use expressions like ~bob and it will expand that to refer to the home directory of the username bob. Use ${BASE:=~uid17} to set the default value to the home directory for user uid17, but don’t put quotes around this string, as that will defeat the tilde expansion.

  • Command substitution is what we used in the example; it will run the commands and take their output as the value for the variable. Commands are enclosed ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.