Bash脚本查找并显示最旧的文件 [英] Bash script to find and display oldest file
问题描述
我正在尝试编写一个脚本,该脚本将显示从中执行脚本的目录中最旧的文件的名称.
I'm trying to write a script that will display the name of oldest file within the directory that the script is executed from.
这是我到目前为止所拥有的:
This is what I have so far:
#!/bin/bash
for arg in $*
do
oldest=$1
if [[ $arg -ot $oldest ]]
then
oldest=$arg
fi
done
echo "Oldest file: $oldest"
我不确定如何增加到下一个文件以检查其是否旧
I'm not sure how to increment to the next file to check if it is older
例如:
oldest=$2
oldest=$3
etc..
在给定以下参数的情况下尝试在bash shell中运行此脚本:
trying to run this script in the bash shell given the following args:
myScript `ls -a`
我得到以下结果:
Oldest File: .
推荐答案
ls
程序具有按时间排序的选项,您可以从该输出中获取最后一个文件::
The ls
program has an option to sort on time and you can just grab the last file from that output::
# These are both "wun", not "ell".
# v v
oldest="$(ls -1t | tail -1)"
如果要避免使用目录,可以事先将其删除:
If you want to avoid directories, you can strip them out beforehand:
# This one's an "ell", this is still a "wun".
v v
oldest="$(ls -lt | grep -v '^d' | tail -1 | awk '{print $NF}')"
我通常不提倡解析 ls
输出,但是对于快速而又肮脏的工作以及了解其局限性来说都是很好的选择.
I wouldn't normally advocate parsing ls
output but it's fine for quick and dirty jobs, and if you understand its limitations.
如果您希望脚本即使对于坚持将控制字符放在文件名中的疯子也可以使用,请使用:-),然后
If you want a script that will work even for crazies who insist on putting control characters in their file names :-) then this page has some better options, including:
unset -v oldest
for file in "$dir"/*; do
[[ -z $oldest || $file -ot $oldest ]] && oldest=$file
done
尽管我建议您通过该链接来理解为什么为什么 ls
解析通常被认为是一个坏主意(因此为什么它在有限的情况下(例如何时)有用?您可以<保证>保证所有文件的类型,例如 YYYY-MM-DD.log
.那里有一串有用的信息.
Though I'd suggest following that link to understand why ls
parsing is considered a bad idea generally (and hence why it can be useful in limited circumstances such as when you can guarantee all your files are of the YYYY-MM-DD.log
variety for example). There's a font of useful information over there.
这篇关于Bash脚本查找并显示最旧的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!