APLawrence.com -  Resources for Unix and Linux Systems, Bloggers and the self-employed

Shell script cannot test for the existence of files

Got questions? Go ahead: Ask me anything!

Anonymous asks:

My shell script needs to move certain files to another location. How do I test that the files exist?

The script you supplied looks like this:


if [ -f /home/sales/*.xml ]
 then

 mv /home/sales/*.xml /tmp

fi
 

Your problem is that "/home/sales/*.xml" can expand to more than one file. The "mv" doesn't care, but test ("[") can't handle that. That's why your script won't work.

You can do this instead:

for i in  /home/sales/*.xml
do
mv $i /tmp
done
 

If there is nothing in /home/sales to match *.xml, the loop won't move anything, but will error. To suppress the errror add "2>/dev/null after the "done".

An equivalent loop in Perl doesn't need the error redirection:

#!/usr/bin/perl
@files=<foobahjj*>;
foreach  (@files) {
  # Nothing in this loop will execute if there are no foobahjj* files.
  print $_
  print "goo"
}
 


Got something to add? Send me email.





(OLDER)    <- More Stuff -> (NEWER)    (NEWEST)   

Printer Friendly Version

-> -> Shell script cannot test for the existence of files



Increase ad revenue 50-250% with Ezoic


More Articles by

Find me on Google+

© Anthony Lawrence



Kerio Samepage


Have you tried Searching this site?

Support Rates

This is a Unix/Linux resource website. It contains technical articles about Unix, Linux and general computing related subjects, opinion, news, help files, how-to's, tutorials and more.

Contact us