Jonny07
Jonny07

Reputation: 625

Check if directory exists not working

I have a textfile (qrs.txt) which contains dir names (one per line) and on my server in the same directory as the script I have those folders with corresponding names from the text file.

This is my script:

#!/bin/bash

while read p; do
  if [ ! -d "$p" ];
    then
        echo "ERROR $p" >> log.txt
    else
        echo "GOOD" >> log.txt
    fi
done < qrs.txt

qrs.txt:

1992300000183805
1992300001176204
1992300002145500
1992300003104507
1992300004104902
1992300005133703
1992300006117802
1992300007144501
1992300008172803
1992300009189005
1992300010146307
1992300011151700
1992300012190007
1992300013126802
1992300014111508
1992300015193908

When that if statement is inside the loop it always returns error which is incorrect because I can see the folders exist. When I take it out of the loop and check for just 1, it works fine... When I echo $p on the same line as error, I can see the file name its checking is indeed correct.

What am I missing here..?

EDIT:

Screenshot of qrs.txt in hex mode:

http://i.snag.gy/25mqJ.jpg

RESOLVED!

My qrs.txt was in [dos] format originally but once converted to unix format using ":set ff=unix" the script worked like a charm!

Upvotes: 0

Views: 886

Answers (2)

user195488
user195488

Reputation:

Your script works fine.

I copied your script to my local machine. When I put blh blah in the qrs.txt file, I got ERROR for each time I ran your script. I ran it four times. I changed the blh blah to a valid path and I received GOOD.

The directory 1992300000183805 for instance, may be not be a valid path. You need the fully qualified path name! For example, /home/user/1992300000183805.

ERROR blh blah
ERROR blh blah
GOOD
GOOD

EDIT

Looking at @chepner comments, I recreated your problem:

Open your qrs.txt file in vi or vim. You should see ^M at the end of your lines. To remove the ^M characters at the end of all lines in vi, use:

:%s/^M//g

This should fix your problem. If not, in vim type this:

:set ff=unix

save the file.

Re-open qrs.txt in vim, then run the regex above again, or manually delete the ^M.

Or you can use perl:

perl -pi -e "s/\r/\n/g;" <file>

Upvotes: 4

Liv
Liv

Reputation: 6124

OK so looking at your provided file it seems those are relative directory names -- as such current directory is very important when you execute the script. Do you execute the script from its own directory or from the parent directory to all the (sub)directories shown in your example? In other words have you tried:

cd <parent directory>
/path/to/yourscript.sh

?

Not to mention the location of qrs.txt seems to be specified relative rather than absolute path. So if there's no qrs.txt in the current directory I don't think your script would work.

Upvotes: 0

Related Questions