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

102 views Asked by At

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!

2

There are 2 answers

8
Charles Duffy On BEST ANSWER

~ 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).

2
alwayslearning On

either remove the quotes around $location (as suggested by other comments already) or, if you need the quotes for some reason, prefix the command with "eval" like: eval cd "$location" I have just tried the eval method (with quotes around ~) and it works.