[Cialug] [OT]: Shell script globbing

Brown, David [DNR] David.Brown at dnr.iowa.gov
Thu Dec 20 12:58:30 CST 2007


Another way to check if any ".bad" files exist is piping the ls output
to grep, searching for ".bad", with the count flag set and storing this
output in a variable.

E.g.  
      N_bad_files=`ls | fgrep -c ".bad"`

      if [ $N_bad_files -gt 0 ] ;then
        echo bad
      fi



-----Original Message-----
From: cialug-bounces at cialug.org [mailto:cialug-bounces at cialug.org] On
Behalf Of Daniel A. Ramaley
Sent: Thursday, December 20, 2007 11:22 AM
To: Central Iowa Linux Users Group
Subject: [Cialug] [OT]: Shell script globbing

I have what should be a simple shell scripting problem. If any .bad 
files exist, then the script should do some stuff (display an error, do 
some cleanup, and exit, though for testing i've simplified it). So far 
i've come up with 2 solutions, one requiring a variable and running 
"ls", the other requiring a seemingly superfluous "for" loop. Is there a

more elegant solution i've not discovered?

My first attempt, doesn't work because -e expects only 1 argument and 
there may be multiple .bad files:
    if [ -e *.bad ] ; then
        echo Bad
    fi

My first working solution, letting ls handle the glob and doing a string

comparison on the result:
    GLOB=`ls *.bad 2> /dev/null`
    if [ -n "$GLOB" ] ; then
        echo Bad
    fi

My second solution; the "if" is required because if no .bad files exist 
the loop will still run once with file set to the literal "*.bad":
    for file in *.bad ; do
        if [ -e $file ] ; then
            echo Bad
        fi
    done

------------------------------------------------------------------------
Dan Ramaley                            Dial Center 118, Drake University
Network Programmer/Analyst             2407 Carpenter Ave
+1 515 271-4540                        Des Moines IA 50311 USA
_______________________________________________
Cialug mailing list
Cialug at cialug.org
http://cialug.org/mailman/listinfo/cialug


More information about the Cialug mailing list