Trouble using cd command with "~" or "$HOME" in bash scripting
We know that ~ and $HOME refer to the home directory of the current user. (For me echo ~=echo $HOME=pandya).
But I can't use it in bash scripting. Here is a simple example script:
#!/bin/bash
echo -n "Enter Directory Path:"
read dir1
cd $dir1But When executed, it gives error No such file or directory as follows:
$ ./script
Enter Directory Path:~/Desktop
./script: line 4: cd: ~/Desktop: No such file or directoryIf /home/pandya used instead of ~ ,then it is working.
Same problem with $HOME.
Thus, How to properly use cd with ~ or $HOME in such bash scripting?
3 Answers
You can solve this problem by using eval command :
#!/bin/bash
echo -n "Enter Directory Path:"
read dir1
eval cd "$dir1"Because in your code $dir1 will not store ~/Desktop but it will store /home/user/Desktop so you can use eval command .
To understand Eval command Here
5Here's an example which works.
As said before, the expansion of variables from input is the key.
#!/bin/bash
echo -n "Dir:"
read dir1
dir2=`eval echo $dir1`
cd $dir2
pwdOf course, you should not expect that your current shell will change its working directory after script execution. It will remain unaffected.
3The problem is the tilde expansion happens before variable expansion (see man bash for details). Variable expansion happens just once, so $dir1 is expanded, but the string $HOME inside it is not.
It might be easier to specify the directory path as a command line argument instead of using read to read it from the console: the shell will expand it for you:
#!/bin/bash
dir1=$1
cd "$dir1"
pwdand call it like
./script ~/DesktopAnother alternative is to use a file dialog instead of typing the path at all:
dialog --dselect / 20 20 1