用于查找和显示最旧文件的 Bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27097167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Bash script to find and display oldest file
提问by dkon
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=
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
我不确定如何递增到下一个文件以检查它是否较旧
for example:
例如:
oldest=
oldest=
etc..
trying to run this script in the bash shell given the following args:
尝试在给定以下参数的情况下在 bash shell 中运行此脚本:
myScript `ls -a`
I get a result of:
我得到的结果是:
Oldest File: .
回答by paxdiablo
The ls
program has an option to sort on time and you can just grab the last file from that output::
该ls
程序有一个按时排序的选项,您可以从该输出中获取最后一个文件:
# 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}')"
I wouldn't normally advocate parsing ls
output but it's fine for quick and dirty jobs, and if you understand its limitations.
我通常不提倡解析ls
输出,但它适用于快速和肮脏的工作,并且如果您了解它的局限性。
If you want a script that will work even for crazies who insist on putting control characters in their file names :-) then this pagehas some better options, including:
如果您想要一个脚本,即使对于坚持将控制字符放在文件名中的疯子也能工作:-) 那么这个页面有一些更好的选择,包括:
unset -v oldest
for file in "$dir"/*; do
[[ -z $oldest || $file -ot $oldest ]] && oldest=$file
done
Though I'd suggest following that link to understand whyls
parsing is considered a bad idea generally (and hence why it can be useful in limited circumstances such as when you can guaranteeall your files are of the YYYY-MM-DD.log
variety for example). There's a font of useful information over there.
尽管我建议按照该链接了解为什么ls
解析通常被认为是一个坏主意(以及为什么它在有限的情况下很有用,例如当您可以保证所有文件都具有YYYY-MM-DD.log
多样性时)。那里有一种有用的信息字体。
回答by anubhava
You can use this function to find oldest file/directory in any directory:
您可以使用此功能在任何目录中查找最旧的文件/目录:
oldest() {
oldf=
for f in *; do
# not a file, ignore
[[ ! -f "$f" ]] && continue
# find oldest entry
[[ -z "$oldf" ]] && oldf="$f" || [[ "$f" -ot "$oldf" ]] && oldf="$f"
done
printf '%s\n' "$oldf"
}
And call it in any directory as:
并将其在任何目录中调用为:
oldest
回答by Mandar Pande
You may use find
command:
find -type f -printf '%T+ %p\n' | sort | head -1
您可以使用find
命令:
find -type f -printf '%T+ %p\n' | sort | head -1