Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: tilde expansion within the word of parameter expansions

Tags:

bash

shell

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

like image 804
Jinux Avatar asked Oct 15 '25 00:10

Jinux


2 Answers

I know a trick

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

but you should just use $HOME.

like image 111
oguz ismail Avatar answered Oct 17 '25 15:10

oguz ismail


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.

like image 45
jhnc Avatar answered Oct 17 '25 15:10

jhnc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!