PDA

View Full Version : Help with if/then statement


chriscaldes
10-22-2002, 03:53 PM
Here's what I'm trying to do:

Basically - read a folder and build a list of files in it to process - however - I'd like it to abort if there are no files to process..

I think the line if [ $? == 0 ] is the part I'm having trouble with. Is that correct? Here is the rest of the script snippet.

Thanks

${find} ${target} -type f \! -name ".*" | while read fn ;

do
if [ $? == 0 ]
then
echo There are no files to process. >>$destdir/upload.log
exit
fi;
#other stuff goes here...
done;

mervTormel
10-22-2002, 06:32 PM
no, that isn't going to work. if there are no files piped to the while from find, the while never gets into its dirty business. e.g., in an empty dir, try this...

$ find . -type f | while read fn; do echo $fn; done

nothing is echo'd, so the while finished on start because the read was null

the structure if [ $? == 0 ] is wrong. should be one equal sign to check for string equality (i had it wrong in that grep quark filetype thread a while back). see man test.

i think you'll just want to use a counter and if the count is zero after the while, then there were no files to process.

ericw13
10-23-2002, 06:58 AM
Originally posted by chriscaldes
Here's what I'm trying to do:

I think the line if [ $? == 0 ] is the part I'm having trouble with. Is that correct? Here is the rest of the script snippet.

Thanks

${find} ${target} -type f \! -name ".*" | while read fn ;

do
if [ $? == 0 ]
then
echo There are no files to process. >>$destdir/upload.log
exit
fi;
#other stuff goes here...
done;

I'm not sure it's the $? line... this is what I tried in both an empty dir and a non-empty one:


for file in *
do
if [ $? == 0 ]
then
echo No files here, boss!
else
echo There\\'s files in them thar dirs! # \ required to escape the single quote
fi
done


and it worked just fine... you can modify the file glob to fit your purposes... I just used the any file * glob.

Note that there are spaces between [ and $? and also between 0 and ].

Eric

PS This is (ba)sh... not sure what shell you are using, but you can put this in a script with
#!/bin/bash
or
#!/bin/sh
as the first line (assuming bash and/or sh are in /bin)

chriscaldes
10-23-2002, 11:06 AM
This works great - Thanks Mel

#!/bin/sh -vx

find ~/Desktop/To_Upload -type f \! -name ".*" | while read fn;
do
echo $fn;

done

BUT- how do I add an if/then that will abort the script with user notification?

ie: if (there are no files to process) echo There are no files in the folder...

BTW eric - I couldn't get your script to work here properly..

Thanks
Chris

ericw13
10-23-2002, 12:17 PM
Sorry about that... $? gets evaluated for each file in the glob ... I assumed it worked cause it printed once in an empty directory.

You could change the if condition to
if [ $file == "*" ];
which is only true if the wildcard could not be expanded... cause the dir is empty.

But you have a solution, so just ignore me.

Eric