When I use the "Use Default Value" parameter expansion with a tilde (~) in Bash, it behaves differently depending on whether it's quoted. For instance:
echo ${unsetVar:-~}
# /home/foo
In this case, ${unsetVar:-~}
correctly expands to the $HOME
when the variable unsetVar is unset. This shows that the tilde undergoes expansion as expected when it's not enclosed in quotes.
However, when I enclose the parameter expansion in double quotes:
echo "${unsetVar:-~}"
# ~
No tilde expansion. I suppose this is due to the https://www.gnu.org/software/bash/manual/html_node/Double-Quotes.html rule. Although I was aware of that rule beforehand, I thought it applies to only special characters directly within double quotes, like "asdf ~ asdf"
but not to those indirectly within, as shown in the example.
I'm aware that $HOME
can be substituted for ~
. However, I'm interested in finding out if there's a way to force the tilde expansion.
EDIT: ... to force the tilde expansion within one simple command EDIT2: without introducing temporary variables
I know a trick
$ unset x
$ echo "${x:-${_/*/~}}"
/home/oguz
but you should just use $HOME
.
This seems to be portable across all the POSIX shells I can get my hands on:
$ HOME="tilde expansion is protected against splitting"
$ unset x
$ echo "${x:-$(printf '%s' ~/)}"
tilde expansion is protected against splitting/
but you should just use $HOME
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With