Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将Linux目录中最旧文件的日期(时间戳)存储在变量(shell脚本)中_Linux_Shell_Date - Fatal编程技术网

将Linux目录中最旧文件的日期(时间戳)存储在变量(shell脚本)中

将Linux目录中最旧文件的日期(时间戳)存储在变量(shell脚本)中,linux,shell,date,Linux,Shell,Date,我试图在/home/目录下找到最早的日志文件的日期,该文件至少有10天 find /home -type f –name "*.log" –mtime +10 -ls | sort | head - n 1 >>/home/text.txt 我使用+10,因为我需要在10天后找到日期 startDate = cut –d '_' –f20,22 text.txt to get the date. 但此代码无法正常工作。有什么建议吗?看来您要做的是使用find在/home/目录

我试图在
/home/
目录下找到最早的日志文件的日期,该文件至少有10天

find /home -type f –name "*.log" –mtime +10 -ls | sort | head - n 1 >>/home/text.txt  
我使用+10,因为我需要在10天后找到日期

startDate = cut –d '_' –f20,22 text.txt to get the date.

但此代码无法正常工作。有什么建议吗?

看来您要做的是使用find在/home/目录下查找10天以上最旧的日志文件。如果这是您的目标,则可以使用类似以下命令的
find
命令:

find /home -type f -name "*.log" -mtime +10 -printf "%TY%Tm%Td%TH%TM%TS %p\n" | \
sort | head -n 1 >> /home/text.txt
head
命令之前的输出将是按升序排列的文件列表,如下所示(以“*.c”模式显示):

头-n1只取第一个。即:

20140621130603.9932529560 ./fill8bit.c
您可以尝试下一种方法:

oldest=$(stat -f "%m%t%Sm %N" /home/**/*.log | sort -n | head -1 | cut -f2)

说明:

  • find
    查找正确的文件
  • stat
    以“秒选项卡日期”格式打印日期
  • 排序
    按秒(数字)排序-首先是最小的数字(秒)(因此它是最早的)
  • head
    获取第一行(最早的)
  • cut
    删除秒字段
如果您有GNU find,您可以使用
-printf
获取“秒选项卡日期”,而不需要使用
xargs
stat
命令,例如:

find arguments -printf "%T@\t%c\n" | sort -n | head -1 | cut -f2

输出是什么?回想一下,
-mtime+10
10*24小时之后
忽略任何小数部分。您可能需要
9
。或者:
oldest=$(find/home/-type f-name“*.log”-mtime+10-exec stat-f”%m%t%d“{}+| sort-n | head-n1 | cut-f2)
,避免了
xargs
的需要。还有一个小注释;
/home/***.log
符号可能会扩展为一个文件列表,该列表太大,无法放入单个命令的参数列表中。将
find
命令与
+
xargs
一起使用可以避免出现问题。
stat
命令和
-printf
选项(以及
-print0
xargs-0
)正在POSIX上使用GNU扩展。然而,这个问题被标记为Linux,所以这不是问题。
oldest10=$(find /home/ -type f –name “*.log” –mtime +10 -print0 | xargs -0 stat -f "%m%t%Sm" | sort -n | head -1 | cut -f2)
find arguments -printf "%T@\t%c\n" | sort -n | head -1 | cut -f2