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?

#!/bin/bash

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

Output:

$ 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

    $HOME/Music
    

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

    case "$fname" in "~/"*)
      fname="${HOME}/${x#"~/"}"
    esac
    

    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.