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

Shell script cannot test for the existence of files


© 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 ]
 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


Inexpensive and informative Apple related e-books:

Photos: A Take Control Crash Course

Photos for Mac: A Take Control Crash Course

Sierra: A Take Control Crash Course

Take Control of the Mac Command Line with Terminal, Second Edition

Take Control of Preview




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





We made the buttons on the screen look so good you'll want to lick them. (Steve Jobs)




Linux posts

Troubleshooting posts


This post tagged:

Bash

Forum

Perl

Scripting

Shell

Troubleshooting



Unix/Linux Consultants

Skills Tests

Unix/Linux Book Reviews

My Unix/Linux Troubleshooting Book

This site runs on Linode





SCO Unix Sales, Support, & Service

Phone:  707-SCO-UNIX (707-726-8649Toll Free: 833-SCO-UNIX (833-726-8649)
www.SCOsales.com