[Cialug] [OT]: Shell script globbing

Daniel A. Ramaley daniel.ramaley at DRAKE.EDU
Thu Dec 20 11:21:30 CST 2007


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


More information about the Cialug mailing list