7

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
7

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.