I'm encountering a weird issue with using ls
to determine if some path is a folder. I'm trying to verify if a user-input string is a valid directory. I'm using ls -ld
to check the input, and then compare the first character of the output to d
.
I assumed the following code would work, but it doesn't. Other valid paths (that don't start with ~
) DO work as strings.
#!/bin/bash
is_valid_dir() {
echo "input=$1"
ls_result=$(ls -ld $1)
echo "$ls_result"
if [[ ${ls_result:0:1} == d ]]; then
echo "input is a directory"
return 0
else
echo "input is not a directory"
return 1
fi
}
is_valid_dir /home/simon # Works
is_valid_dir . # Works
is_valid_dir ../. # Works
is_valid_dir ~ # Works
is_valid_dir ~/.. # Works
is_valid_dir "/home/simon" # Works
is_valid_dir "." # Works
is_valid_dir "../." # Works
is_valid_dir "~" # Doesnt Work!
is_valid_dir "~/.." # Doesnt Work!
Can somebody tell my why supplying a path relative to ~
will confuse ls
when supplied with ""
?