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.
More Articles by Anthony Lawrence © 2015-07-29 Anthony Lawrence
We made the buttons on the screen look so good you'll want to lick them. (Steve Jobs)
Printer Friendly Version
Shell script cannot test for the existence of files Copyright © July 2015 Tony Lawrence
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