When I input a relative directory path name using the 'read' command in Bash, it is not recognized as a valid directory by the -d test:
Relative directory path ~/tmp fails the if/-d test:
corba@samwise:~$ read CMDLINE_FILENAME
~/tmp
corba@samwise:~$ echo "$CMDLINE_FILENAME"
~/tmp
corba@samwise:~$ if [ -d $CMDLINE_FILENAME ]; then echo "Valid directory!"; fi
corba@samwise:~$
Relative directory path ../tmp fails the if/-d test:
corba@samwise:bin$ read CMDLINE_FILENAME
../tmp
corba@samwise:bin$ echo "$CMDLINE_FILENAME"
../tmp
corba@samwise:bin$ if [ -d $CMDLINE_FILENAME ]; then echo "Valid directory!"; fi
corba@samwise:~$
But an absolute directory path succeeds:
corba@samwise:~$ read CMDLINE_FILENAME
/home/corba/tmp
corba@samwise:~$ echo "$CMDLINE_FILENAME"
/home/corba/tmp
corba@samwise:~$ if [ -d $CMDLINE_FILENAME ]; then echo "Valid directory!"; fi
Valid directory!
corba@samwise:~$
I expected if [ -d ~/tmp ]
and if [ -d ../tmp ]
to be recognized as valid directory names. They were not.
I tried the solution that was offered in How to manually expand a special variable (ex: ~ tilde) in bash, but it only works for tilde and not for other relative paths like ../
, ../../
, or ./
I tried the variations of quoting/double-quoting and single/double square brackets in the if
statement and get the same error in all cases. And these errors occur on MSYS2 (Git Bash) and Ubuntu 22.