EN VI

Bash: tilde expansion within the word of parameter expansions?

2024-03-14 00:00:12
How to Bash: tilde expansion within the word of parameter expansions

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

Solution:

I know a trick

$ unset x
$ echo "${x:-${_/*/~}}"
/home/oguz

but you should just use $HOME.

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login