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