0

I want to see if a folder exists. In the script file if I use:

#!/bin/bash

batch_folder=~/Desktop/
if [ -d $batch_folder ]
then
    echo "Dir exists."
else
    echo "Dir doesn't exists."
fi

I get as result the correspoding echo. But when I prompt for the path with the read command I'm getting everytime that the directory doesn't exists even if it indeed exists. This is my script:

#!/bin/bash

read -e -p "Batch folder location: " batch_folder
if [ -d $batch_folder ]
then
    echo "Dir exists."
else
    echo "Dir doesn't exists."
fi

I also tried in the if statement to use as variable "$batch_folder", ${batch_folder}, "${batch_folder}" but none of these works.

I know that the problem is in how the read command saves the variable, because in my first example, if I set batch_folder='~/Desktop/' I'm getting the same result as with the read command.

Jordan Cortes
  • 271
  • 1
  • 2
  • 16

2 Answers2

3

I’m going to assume you’re typing the tilde at the prompt. Expansion of ~ is a shell feature that takes place on script tokens and not on arguments or input in general.

You can expand it manually:

batch_folder="${batch_folder/#\~/$HOME}"
Ry-
  • 218,210
  • 55
  • 464
  • 476
0

First of all, quote the variable:

if [ -d "$batch_folder" ]

Secondly, evaluate the content in the variable (expand chars like ~):

...
eval batch_folder="${batch_folder}"
if [ -d "$batch_folder" ]
...

The first remark will fix the problem for dirs containing spaces, the second will resolve the issue of dirs containing ~ etc.

ShellFish
  • 4,351
  • 1
  • 20
  • 33