I have a scripts which run at every 1 min and do some job.
this scripts look for the file in the directory and move in the other directory.
I want to write a line which forst check if the *.LOG file exist in the directory
if *.LOG exist
then
do for i in *.LOG
load
move
fi.
how can we check if the .LOG files exist in the directory and then execte else come out without failure, at present it gives error if it doesn't fine any file there.
for file in *.LOG; do
[ -e "$file" ] || exit 0
... the rest
done
This way, if .LOG does not expand (no file matches), then testing if '.LOG' exists with -e will fail and your script will exit successfully and crontab should not email you
Check out the -e switch of the test command. You can also take single square brackets to resemble the test command or use double square brackets to use the shell's internal test.
You can also have a look into the man page of test or your shell to see which switches are available.
And please use code tags, even this up there is just pseudo code, thanks.
if [ -f *.LOG ]
then
for i in *.LOG
do
load
move
done
fi
.... might do it, however it's not really necessary. You have a loop based on the file name too. If there are no files, then the loop will not execute.
Did you try my code with [ -e "$file" ] || exit 0 yet? I do believe this is a much better approach. There are pitfalls to parsing ls. ls produces a list for humans to read. The shell can already produce a working set of files with globbing. For example, files with spaces, and even directories:
$ touch 'file with spaces.log'
$ mkdir 'directory.log'; touch 'directory.log/file1' 'directory.log/file2'
$ for file in *.log; do echo "$file"; done
directory.log
file with spaces.log
$ for file in `ls -1 *.log`; do echo "$file"; done
file
with
spaces.log
directory.log:
file1
file2
You see that ls is not good for parsing. It's likely you can be certain your directory will not have files with spaces, nor directories with .LOG ending, but it's good practice. So I suggest simply adding a test inside the loop. This should do as well:
for log in *.LOG
do
[ -f "$log" ] || continue
load
move
done