Click to See Complete Forum and Search --> : quick IF question


pickarooney
03-02-2004, 06:14 PM
trying to add a line in a bash script to say "if there are any files then do the following".
if I do it only for specific files it's fine - if [ -ef *.txt ]
then

but if I put in * or *.* instead of *.txt the shell interprets it as a wildcard and tries to apply it to the pwd.
Hope that makes sense.
Alternatively a multifilter like id [ -ef *.txt|*.doc|.zip ] would work, but that syntax is wrong.

Modorf
03-02-2004, 06:46 PM
if [ -ef .*\..{3} ]
then


This will find all files that have == *.???
Look up regular expressions. That will explain why your have to escape code the '.'

. matches any character

n

http://tille.soti.org/training/bash/ch04.html

bwkaz
03-02-2004, 08:32 PM
But test (and therefore [) don't use regular expressions...

The problem is that bash does the wildcard expansion (wildcard expansion is NOT the same as regex expansion -- regexes are more powerful in that they can match strings that wildcards can't) before the program runs. It expands *.* into all filenames containing a period anywhere in their names, and "test" errors out when there's more than one operand to -e or -f (incidentally, you can get rid of the -e test there; -f is "-e plus it's a regular file").

What you can do is:

firstfile=$(echo *.* | cut -d' ' -f 1)

if [ -f $firstfile ] ; then
# do whatever
fi This way, the argument to -f is always only one file. It will break, however, if there are any filenames with spaces in them that match your wildcard, so you'll want to be careful of that.

pickarooney
03-03-2004, 03:22 AM
Tricky bugger, isn't it? :)

I used a similar clunky workaround for the time being...anyfiles=`ls|head -1`
if [ "$anyfiles" != "" ]
then
dostuff
fi

the.spike
03-03-2004, 04:34 AM
Originally posted by bwkaz
"test" errors out when there's more than one operand to -e or -f

This is not strickly true.. I've just coded the following..

if [ ! -f $INPUT_FILES.Z ]
then

where INPUT_FILES="DM_ASL_G_*.DAT"

and it works a treat where there are multiple files (Had to test it as I wasn't sure that I ever had!). Could be related to the fact that I am doing a ! -f instead of a -f though...

spike...

bwkaz
03-03-2004, 08:08 PM
Hmm...

[ -f one two ]

and

[ ! -f one two ]

both give:

bash: [: one: binary operator expected

while

[ -f one ]

and

[ ! -f one ]

give no output (and the return value is set appropriately).

However, it works differently when bash expands variables containing glob characters, apparently. I thought it would do glob expansion when setting the variable, but apparently it does it when evaluating the command that uses the variable. Huh.