The UNIX and Linux Forums

The UNIX and Linux Forums (http://www.unix.com/index.php)
-   Shell Programming and Scripting (http://www.unix.com/shell-programming-and-scripting/)
-   -   Script to check file exists (http://www.unix.com/shell-programming-and-scripting/166140-script-check-file-exists.html)

ch33ry 08-26-2011 05:03 PM

Script to check file exists
 
Hi,

I am trying to write a script which checks if any file exists with "*.log" or "*.out" in Directory

below is the code
Code:

#------------------
path=/abd/xyz/
if [ -f "$path *.log -o *.out" ]; then
echo "Good"
else
echo "Failure"
fi
#--------------------------

its always going to else part and printing "Failure" even for TRUE condition.

Can anyone correct me where i am wrong.

Thanks in Advance.

cjcox 08-26-2011 05:44 PM

Perhaps more difficult than it seems... if you want to be portable and without many issues. You see a wildcard is expanded by the shell.. this means that for sufficiently large matches, you'll blow up the command line (imagine *.txt matching thousands of files in the current directory and all of that fitting onto the command line).


So... it might be more portable to do an ls and filter for matches, quitting on first matched occurrence.

Code:

path=/abc/xyz/
files=`ls "${path}" | sed -n -e '/\.log$/ { p;q; }' -e '/\.txt$/ { p;q; }'`
if [ "$files" ]; then
  echo "Good"
else
  echo "Failure"
fi


Depending on shell and utilities available, there may be some less portable solutions for this. The one I show here should work just about anywhere there is a bourne shell compatible shell and some reasonable flavor of sed.

ch33ry 08-26-2011 05:51 PM

Code:

set -vx
path=/a/i/logs
if [ -f "$path" "a.log" -o "b.log" ]; then
echo "Success"
else
echo "Failure"
fi

Hi....

How abt for the above lines i am searching for existence of a files.

What is difference between -a and -f.

Thanks for your response.

dude2cool 08-26-2011 06:04 PM

Change
Code:

"if [ -f "$path" "a.log" -o "b.log" ]"
to
Code:

if [ -f "$path" "a.log" -o -f "b.log" ]

ch33ry 08-26-2011 06:13 PM

I've changed the code....but still its not working....

in the above i am checking for existence of two files with a.log and b.out in the directory logs...

its returing Failure if the files are not existing, its correct as expected
but when the file are existing its returing "Failure" again.

So i am bit confused.....

dude2cool 08-26-2011 06:22 PM

oops sorry :), try the below statement. I did not look close enough before posting.

Code:

if [ -f $path/*.log -o -f $path/*.out ]

ch33ry 08-26-2011 09:28 PM

Thanks a lot...it worked perfectly................


All times are GMT -4. The time now is 07:32 AM.

Linux and Unix Supported by: vBulletin
Search Engine Optimisation provided by DragonByte SEO v1.1.4 (Pro) - vBulletin Mods & Addons Copyright © 2014 DragonByte Technologies Ltd.
The UNIX and Linux Forums Content Copyright ©1993-2013. All Rights Reserved.
Forum Operations by The UNIX and Linux Forums