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 ]

 mv /home/sales/*.xml /tmp


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
mv $i /tmp

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:

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?

Unix/Linux/Mac OS X support by phone, email or on-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

Better to fight for something than live for nothing. (George S. Patton)

What happens then? Is there a ticker tape parade and heartfelt thanks from the computer it has reached? No, my friends, there is not. The poor packet is immediately gutted, stripped of its protective layers and tossed into the hungry maw of whatever application (mail, a webserver, whatever) it belongs to. (Tony Lawrence)

This post tagged: