Reputation: 117
I am required to create a script in linux bash, where at some point the user can enter a path to a directory. For this I should use read -p
command. Then I should check if directory exists. My code below works fine until the user tries to enter ~/path
. The code does not recognize symbol ~ as Home directory. Any suggestions?
read -p "Please, enter the destination: "
if [ -d "$REPLY" ]; then
echo "Directory exists!"
fi
Upvotes: 1
Views: 205
Reputation: 80931
In general you should avoid (and encourage people to avoid) using ~
expansion except directly at the shell prompt.
That said if you do have to deal with it and want to support all of the various extended bash tilde expansions you can use something like my tildeExpand.sh script.
Upvotes: 1
Reputation: 6181
You'll have to replace ~
with "$HOME"
yourself. There are also other types of tilde expansion, which you generally use less often, such as ~user
to get user's homedir instead of your own. Assuming you only care about the first case, then a parameter expansion will do
read -ep 'Please, enter the destination: ' dir
dir=${dir/#~/$HOME}
if [[ -d $dir ]]; then
printf 'Good job, the directory exists!\n'
fi
You might notice I added -e to the read command. This makes read use the readline library to read in the directory. That means the user may use tab-completion.
See BashFAQ 100 for more on string manipulations in bash.
Upvotes: 4