Search code examples
shellunixcd

Cd 'ing to a directory by reading the argument for 'cd' from a file


I've written a script to change directory (cd) by reading the value for cd from a file. But when I run this script I run into "No such file or directory" error.

This is the script I've written:

#!/bin/bash
while read line  
do
IN=$line
set -- "$IN"
IFS=":"; declare -a Array=($*)
echo "File location : ${Array[1]}"
location=${Array[1]}
echo "Location : $location"
cd "$location"
echo "Pwd :"
pwd
done < location.properties

Contents of location.properties file:

A:~/Downloads

Output:

File location : ~/Downloads  
Location : ~/Downloads  
./script.sh: line 10: cd: ~/Downloads: No such file or directory  
Pwd :  
/home/path/to/current/dir

Both the echo statements print the location correctly but cd to it fails. Any help is appreciated! Thanks in advance!


Solution

  • ~ isn't expanded by quotes. I generally suggest considering it an interactive feature only, and unavailable in scripts -- as the side effects from unquoted expansions in scripts aren't worth that particular benefit.

    To perform this expansion step yourself:

    if [[ $location = "~/"* || $location = "~" ]]; then
      location=$HOME/${location#"~"}
    elif [[ $location = "~"?* ]]; then
      user=${location%%/*}
      user=${user#"~"}
      read _ _ _ _ _ home _ < <(getent passwd "$user")
      location="$home/${location#*/}"
    fi
    

    Of course, this is overkill, and the usual practice is to assume that scripts won't handle paths containing ~ if not expanded before their invocation (as by a calling shell).