0

I have a bash script that will ssh -tq into remote box and will do several commands. Something like this:

if [[ $answer = 1 ]] ; then
        ssh -tq box "
        cd /biglogs/
        sudo ls -g ./$host1/2017/$month1 | tail -5
        sudo tail  /$folder1/$host1/`date +%Y`/$month1/`date +%d`/$host2"
fi

All variables are defined before ssh into remove box. My problem is that I'm not sure how I can tail out latest text file. As you can see currently the sudo tail will go into /folder1/$host1/`date +%Y`/$month1/`date +%d`/$host2".

$host1 and folder and $month are defined by user input before the ssh. What I want is for this script to tail the latest text document inside folder $month.

The dir format is as follow test1.test.t/2017/08/31/test1.test.1.txt currently my script will try and tail the text document with date of current day so if I was to input month 02 (query would be test1.test.t/2017/02/) the script would add 31 (today) so it would be test1.test.t/2017/02/31/ which we both know its not correct.

For person who marked it as dupe and to use -d I don't think that is correct. The folder structure is /folder1/host/year/month/day/host.log Currently the script will take actual date for example today 2017/08/31 but what if the box has been offline since 2017/08/20 therefore there will be no log file in folder 2017/08/31. My script will try current date despite that. My question is how can I force the script to use the last date in the month folder

k3mp3r
  • 13
  • 4

1 Answers1

0

You can check a date before you do ssh:

year=$(date +%Y)
month1="02"
day=$(date +%d) # current day is 31

date -d "$(date +%Y-${month1}-${day})" 2>/dev/null
# date: invalid date ‘2017-02-31’

# if date fails
if [[ $? -ne 0 ]]; then
    day=$(date -d "$(date +%Y-$((month1 + 1))-01) -1 day" +%d)
fi

echo ${year}-${month1}-${day}
# prints: 2017-02-28

so in your script use:

sudo tail  /${folder1}/${host1}/${year}/${month1}/${day}/${host2}
sKwa
  • 889
  • 5
  • 11
  • Not sure that would work the way I need. This script would be used to check the logs for specific hosts. Sometimes hosts die and the logs will be empty so for example today is 31st and the box died on the 28th. There will be no files called 31st and the only files you will find in the month dir will be 28th - 1st – k3mp3r Aug 31 '17 at 02:36