Skip to content
Advertisement

condition match with find and if else in bash

I want to see the files which are before 15 days modified into a directory.

if not found before 15 days, then look for 10 days before.

My Attempt

#!/bin/bash
FILE_DIR1="/var/log/"
diskClean (){
FileExist=`sudo find $FILE_DIR1 -mtime +15 -type f -exec ls -la {} ;|awk '{print $9}'`

if [ -f $FileExist ]
then
   echo "these are the files before 15 days."
   ls $FileExist
else
   FILE=`sudo find $FILE_DIR1 -mtime +10 -type f -exec ls -la {} ;|awk '{print $9}'`
   echo "these are the files before 10 days." 
   ls $FILE     
fi
}
diskClean

Advertisement

Answer

FileList is a string which holds the names of all files (separated by spaces), for instance something like /var/log/foo /var/log/bar. You then test in your condition whether you have one file where the name equals the value of this string. While you have a file with name “/var/log/foo”, you don’t have one with the name “/var/log/foo /var/log/bar” and the condition will fail.

You could use

if [[ -n "$FileList" ]]

instead.

BTW, what is the point to first list the files with all attributes (ls -l), and then use awk to extract just the filename? If you are interested in the filenames only, you could either use ls -1, or even better omit the -exec clause completely; find will output the filenames anyway.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement