UNIX & Linux Forums

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

ch33ry 08-26-2011 06:03 PM

Script to check file exists

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

below is the code

if [ -f "$path *.log -o *.out" ]; then
echo "Good"
echo "Failure"

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 06: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.


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

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 06:51 PM


set -vx
if [ -f "$path" "a.log" -o "b.log" ]; then
echo "Success"
echo "Failure"


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 07:04 PM


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

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

ch33ry 08-26-2011 07: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 07:22 PM

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


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

ch33ry 08-26-2011 10:28 PM

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

All times are GMT -4. The time now is 06:59 AM.

UNIX and Linux Forums
Search Engine Optimisation provided by DragonByte SEO v2.0.32 (Pro) - vBulletin Mods & Addons Copyright © 2017 DragonByte Technologies Ltd.
Unix & Linux Forums Content Copyright©1993-2017. All Rights Reserved.
Forum Operations by The UNIX and Linux Forums