I'm working on a bash script to move files from one location, to two. The first part of my challenge is intended to check a particular directory for contents (e.g. files or other items in it), if files exists, then send the list of names to a txt file and email me the text file. If files do not exist, do nothing. It's not working as intended. Mailing the file is fine. Checking for contents, sending contents to file, is not. Assistance is appreciated.
Here's where I am.
file2=/directory/file/*
file=/usr/local/mailfile.txt
if [ -f ${file2} ];
then
ls -la $file2 > $file
fi
if [ -s ${file} ] ; then
mail -s "$Subject" "$Recipients" < $file
fi
file2 variable will expand to multiple values (file names from directory specified)
It cannot be used in if [ -f $file2 ] .. , the error will be to many arguments (it expects one not a list of files).
I cannot be sure about the exact requirement from your post..
file2=/directory/file/* # lets create a variable which contains all the files in a directory.
file=/usr/local/mailfile.txt
if [ -f ${file2} ]; # if a file exists (this will work only if a one file is a file2 directory)
then
ls -la $file2 > $file # list all the files into a txt file ? You could do these without any variables or conditions ...
fi
....
So the entire code can be :
ls -al /directory/file/* > ${file}.txt
if [ -s ${file}.txt ]; then # if ls output gave something to file.txt (there are files)
... mail or whatever
else
printf "%s\n" "Directory is empty, will do nothing"
fi
Thanks for your response, Peasant. I had decided to do the following before your response, and is working great. It looks to see if any files exists, sends the contents to a text file and emails the output of the file. If no items exists in the directory, it does nothing. This is only a quarter of the entire script and what needs to be done. I may be posting additional questions on this.:
dir=/directory/file/*
file=/usr/local/mailfile.txt
if [ "$(ls -a $dir)" ] ; then
ls -la $dir > $file
else
:
fi
if [ -s ${file} ] ; then
mail -s "$Subject" "$Recipients" < $file
fi
ls -al $dir > $file &&
if [ -s $file ]; then mail -s "$Subject" "$Recipients" < $file ; fi ||
printf "%s\n" "No files in directory or some other ls exit code error"
Is the logic okay?
I would prefer a straight logic
if ls -al $dir > $file && [ -s $file ]
then
mail -s "$Subject" "$Recipients" < $file
else
printf "%s\n" "No files in directory or some other ls exit code error"
fi