I am new to bash shell scripting. Converting over to Linux before support for Windows XP fades into the sunset, I am redesigning and rewriting many scripts that worked using enhanced scripting language Take Command.

I am trying to evaluate whether a directory exists based on a list of directories in a text file. If I enter the following at the command line:

if [ -d "/media/D_Drive/Music/Rolling_Stones/1995-Voodoo_Lounge/" ]; then echo "True"; else echo "False"; fi

True echos to cli.

If I try:

while read line; 
if [  -d "$line" ]; then
    echo "exists $line";
    echo "Does not Exist - $line";
done < /media/D_Drive/Music/Albums-linux.txt 

all the values of $line come back as not existing

What am I missing? I have tried [ -d "$line" ] with and without quotes. I know it does not have to do with possibility of whitespace in the sub-directory name for that triggers a too many arguments error.

4 Years
Discussion Span
Last Post by FelineHazard

Your assignment seems correct.
I'd suggest you check the values in $line, by using echo. Perhaps it is being prefixed by "/" or some special charater. Also - remember: The script assumes you are checking for directories found in the directory in which it was executed. If you enter/leave a directory that might explain why -d fails.
My guess is that you enter manually directory name, and then press return. So $line has a terminal \n character. Try removing the terminal newline and I think it would work. Perhaps this would work:

line2=`echo -n $line`;  

Instead of $line, create $line2. the echo -n command ensures that no newline is echoed at the end of the string.

Edited by FelineHazard



I did some more research and discovered the command bash -x scriptName.sh which runs the script in a debug mode so one can monitor the activity of a script. I discovered that my file containing the sub-directories was terminating in \r. \n was being removed with incorporating your suggestion of

   line2=echo -n $line  

it was just a matter of changing the encoding to UTF-8 and ending the lines in Unix instead of Windows format.

A good article for learning the debug features of bash scripting can be found at http://aymanh.com/how-debug-bash-scripts

As for the path being relative or absolute, it does not make a difference if I am in the root of the sub-directories or not. The file which contains the list of sub-directories contains paths which are absolute to the root


All is working well now. Thanks for your input.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.