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
~boband it will expand that to refer to the home directory of the usernamebob. Use${BASE:=~uid17}to set the default value to the home directory for useruid17, 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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access