This question already has answers here:
Get the latest file in directory [duplicate]
(2个答案)
两年前关闭。
我有一个bash脚本,它将ssh -tq放入远程框中,并执行几个命令。
像这样的:
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

所有变量都是在ssh进入remove box之前定义的。我的问题是,我不知道如何才能写出最新的文本文件。正如你现在看到的,sudo尾部将进入/folder1/$host1/`date +%Y`/$month1/`date +%d`/$host2"
$host1和folder和$month由ssh之前的用户输入定义。我想要的是这个脚本在文件夹$month中跟踪最新的文本文档。
dir格式如下
当前,我的脚本将尝试在文本文档中添加当前日期,因此如果我要输入第02个月(查询将是test1.test.t/2017/08/31/test1.test.1.txt),脚本将添加31(今天),因此它将是test1.test.t/2017/02/,我们都知道它不正确。
对于那些将其标记为dupe并使用-d的人,我认为这是不正确的。
文件夹结构是
/文件夹1/host/year/month/day/host.log
当前脚本将以实际日期为例,日期为2017/08/31
但如果自2017年8月20日起,盒子一直处于脱机状态,那么文件夹2017年8月31日将没有日志文件。尽管如此,我的脚本仍将尝试当前日期。我的问题是如何强制脚本使用month文件夹中的最后一个日期

最佳答案

您可以在执行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

所以在你的剧本中使用:
sudo tail  /${folder1}/${host1}/${year}/${month1}/${day}/${host2}

关于linux - ybash在syslog文件格式内使用最新日期,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45971495/

10-11 22:15
查看更多