Bash script change directory returns no such file or directory
Emily Wong
I'm working a script that reads back the input of a full path to a directory (e.g. ~/test) but when I run the shell script it come back with this:
test-script.sh: line 34: cd: ~/test: No such file or directory
I'm running the test-script.sh file in a different directory, so I was assuming that a simple:
cd ~/test in the script would do it, but I guess not.
I know that this is probably a redundant question, but most of the other issues/examples have been with loops and other cases outside of just doing a simple cd ~/test in a script.
And for reference this is all I'm doing in my script:
echo What directory do you want to change to?
read directory_name
cd $directory_nameAgain, new to bash/shell scripting so if there are any other ideas or suggestions, I'm all for it. Thanks!
21 Answer
solution 1)
if you want to use ~ , you need to use eval .
#!/bin/bash
pwd
echo What directory do you want to change to?
read directory_name
eval "cd $directory_name"
pwdBut this solution is weak , because someone can enter some maliciuois command instead of a directory name and this script will execute .
solution 2) check if the first character of directory_name is a ~ and replace it by the appropriate value , it can the current user home dir or another user home dir .
you can do cd ~ or cd ~usera to change to usera homedir
1