Hello, I am trying to write a shell script in unix which looks for the last two files in a folder, checks their size and reports(via mail) if either of their file size is =0.
cd /tmp
list last two files: ls -ltr | tail -2
check if size of any of these two files is 0
if true, then send a mail(can use mailx I suppose) else exit
could you please suggest me the ways of achieving this as I am very new to shell scripting..Thanks in advance!
Kiran.
#! /bin/bash
for file in $(ls -rt | tail -2)
do
if [ ! -s $file ]
then
echo " $file has size 0 ;-) " | mailx -s "This is subject" mailid@domain.com
fi
done
1 Like
Hello,
Could you please use the following code.
please give your mail address as well as PATH will be the path where you want to test the files.
Please let me know in case you have any queries.
Also please don't place the script within same directory.
cat test.ksh
PATH=/home/test_user/bin/singh_testing
cd $PATH
zero=0
# zero shows variable here.
a=`ls -ltr | tail -2 | awk '{print$5}'`
echo $a
set -A value ${a}
for i in ${value[@]}
do
if [[ ${i} -eq ${zero} ]]
then
echo "Non zero file found."
mailx -s "file size found NON 0 please check" Ravinder_Singh1@test.com
fi
done
echo "Script done"
ksh test.ksh
Thanks,
R. Singh
Thankyou for the responses..I have used the following and it is working now.
However, is there a way to include checking the same criteria in a different directory as well ?
present code:
#!/bin/ksh
typeset SERVER=$(hostname)
MAIL="kiran@test.com"
LOGDIR=/tmp/log1/
cd $LOGDIR
for file in $(ls -rt | tail -2)
do
if [ ! -s $file ]
then
echo " $file has size 0 under $LOGDIR" | mailx -s "Error in executing script on $SERVER" $MAIL
fi
done
===========
As you can see, presently I am checking in /tmp/log1..can I also add to check for this condition in /tmp/log2 as well ?
Thanks.
Kindly try to use the following code.
#!/bin/ksh
typeset SERVER=$(hostname)
MAIL=kiran@test.com
set -A LOGDIR
LOGDIR[0]=/tmp/log1/
LOGDIR[1]=/tmp/log2
cd $LOGDIR
for j in LOGDIR[@]
do
cd $j
for file in $(ls -rt | tail -2)
do
if [ ! -s $file ]
then
echo " $file has size 0 under $LOGDIR" | mailx -s "Error in executing script on $SERVER" $MAIL
fi
done
done
Thanks,
R. Singh
1 Like
Thanks to you all..used nested for loops and it is working now.
Will test it and comeback if any further modifications are required
Or if you want to test arbitrary directories at runtime, you can specify them as arguments to the script in the command line. You will then have to make the script loop as many times as arguments to the script you specified previously. That way you don't have to hardcode the directories inside the script.
I am trying to modify the script to include checking for the filesize and report if it is less than average of the files present in the directory.
I can find average file size using the below command, but how do I check if any of the last two file size is less than the average size ?
AvgFileSiz=$(ls -l | awk '{s+=$5} END {s/NR/1024/1024 "MB"}')
Please help. Thanks