Search code examples
bashvariablesfindpathname

Bash terminal does not recognize a path in a variable because of the "~"


For example if I type ~ or ~/Documents as an input I get the message : No such file or directory

However if I use /home/username/Documents it works fine.

echo "Dose onoma katalogou"

read Directory

find $Directory -type f -perm 777

Any idea on why this happens and how I could fix it in order to be able to type pathnames including "~"?


Solution

  • bash expands the variable $Directory after it expands any ~, thus once $Directory is expanded, the time to expand ~ has passed.

    eval find $Directory -type f -perm 777
    

    will work because eval will see the ~ and run shell expansion again.

    You may test the effect by simpler commands:

    tilde='~'
    echo $tilde            # prints a literal ~
    eval echo $tilde       # prints your home directory
    

    By the way, a directory names containing blanks will cause problems.