Need help on if test condition

Posted on

Problem :

Need your help on below script where I am testing if file found at location /log/TestFile* and id there is only one file then it will display “File successfully Found” else “note found”. my second condition – [ $sfCount == 1 ]; is not working. please help me with that.

sfCount=`ls -l /log/TestFile* | awk '{print $9}'| wc -l |sed "s/[[:blank:]]//g" | sed '/^$/d' | sed 's/n//g'`
sFile=`ls -l /log/TestFile* | awk '{print $9}'`

if [ -e /log/$sFile ] && [ $sfCount == 1 ]; then
    echo "File successfully Found"
    exit 0
else 
    echo "File Not found"
    exit 1
fi

Solution :

You can get the file count much more easily by doing the following:

ls /log/TestFile* | wc -l

That will relieve you of all the other.
I’m not sure why you are getting a count of the number of files, and also putting them into an array to see if they exist. From what it looks like, you just want to see if they exist. You only need the first command for that. So, what we are left with is:

if [ $(ls /log/TestFile* 2>/dev/null | wc -l) != 0 ]; then
    echo "File Found"
else 
    echo "File not found"
fi

The “2>/dev/null” will suppress output to STDERR if there are no files found. We simply want 0, or not 0.

Sorry, I have to correct above and its working fine

----------------- Script start here ------------------------- 
sfCount=ls -l /log/TestFile* | awk '{print $9}'| wc -l |sed "s/[[:blank:]]//g" | sed '/^$/d' | sed 's/n//g' 
sFile="TestFile*"

if [ -f $IB_DIR/$sFile ] && [ $sfCount == 1 ]; then
    echo "File successfully Found"
    exit 0
else 
    echo "File Not found"
    exit 1
fi

Leave a Reply

Your email address will not be published. Required fields are marked *