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

Shell script cannot test for the existence of files

Some material is very old and may be incorrect today

© July 2015 Anthony Lawrence

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"

If you found something useful today, please consider a small donation.

Got something to add? Send me email.

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

Printer Friendly Version

-> Shell script cannot test for the existence of files

Inexpensive and informative Apple related e-books:

Take Control of Pages

Take Control of OS X Server

Take Control of iCloud, Fifth Edition

El Capitan: A Take Control Crash Course

Take Control of iCloud

More Articles by © Anthony Lawrence

Printer Friendly Version

Have you tried Searching this site?

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

Printer Friendly Version

Random numbers should not be generated with a method chosen at random (Donald Knuth)

Linux posts

Troubleshooting posts

This post tagged:







Unix/Linux Consultants

Skills Tests

Unix/Linux Book Reviews

My Unix/Linux Troubleshooting Book

This site runs on Linode