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 $dir1 

But 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 directory 

If /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?

2

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

5

Here'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 pwd 

Of course, you should not expect that your current shell will change its working directory after script execution. It will remain unaffected.

3

The 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" pwd 

and call it like

./script ~/Desktop 

Another alternative is to use a file dialog instead of typing the path at all:

dialog --dselect / 20 20 
1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy