Bash – readlink literal vs variable

bashquotingshelltildevariable substitution

Using BASH: the answer is probably obvious but, not for me.

> echo $PWD
/root/fcm
> readlink -f ~
/root
> # but then with a variable or literal
> a='~'
> readlink -f $a
/root/fcm/~
> readlink -f "~"
/root/fcm/~

I'm expecting to receive just '/root/';
Who is doing the substitution bash or readlink?

Best Answer

The shell does the tilde expansion. readlink doesn't. Bash will not expand tilde within quotes.

readlink -f $a does not do what you want as tilde expansion happens before variable expansion, i.e. the variable is expanded to ~, but that tilde won't be expanded further.

The order in which Bash do things is: brace expansion, tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, word splitting, and pathname expansion.

Using $HOME may be preferable to using tilde under some circumstances, since it behaves as any other variable.

Also, please don't work logged in as root...