Ubuntu – Why isn’t tilde expansion performed on the input to read

bashcommand linescripts

Why has tilde expansion not occurred in the output of this script?


read -p "Enter filename: " fname
if [[ -d $fname ]]
        echo "$fname is a directory"
        echo "$fname is not a directory"


$ bash -x test_cd.sh 
+ read -p 'Enter filename: ' fname
Enter filename: ~/Music
+ [[ -d ~/Music ]]
+ echo ' ~/Music is not a directory'
 ~/Music is not a directory

Best Answer

  • That’s simply because read doesn’t perform tilde expansion before saving the string, neither is it performed on a variable content later. You can use $HOME instead and enter


    or let the script test for ~/ and replace it (taken from this answer):

    case "$fname" in "~/"*)

    You can also use bash Parameter Expansion to replace ~/ with $HOME at the beginning of the string:

    if [[ -d ${fname/#~\//$HOME\/} ]]

    This variable is expanded before the substitution is performed.