bash 获取目录中的最新文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15041473/
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
Get the latest file in directory
提问by Ashot
I need to get the latest directory name in a folder which start with nlb.
我需要在以 nlb 开头的文件夹中获取最新的目录名称。
#!/bin/sh
cd /home/ashot/checkout
dirname=`ls -t nlb* | head -1`
echo $dirname
When the folder contains many folders with name starting nlb, this script works fine, but when there is only one folder with name starting nlb, this script prints the latest file name inside that folder. How to change it to get the latest directory name?
当文件夹包含许多名称以 nlb 开头的文件夹时,此脚本可以正常工作,但是当只有一个名称以 nlb 开头的文件夹时,此脚本会打印该文件夹中的最新文件名。如何更改它以获取最新的目录名称?
采纳答案by John Zwinck
Add the -d
argument to ls. That way it will always print just what it's told, not look inside directories.
将-d
参数添加到 ls。这样它总是会打印它告诉的内容,而不是查看目录内部。
回答by janos
#!/bin/sh
cd /home/ashot/checkout
dirname=$(ls -dt nlb*/ | head -1)
echo $dirname
As the other answer points it out, you need the -d
to not look inside directories.
正如另一个答案指出的那样,您需要-d
不要查看目录内部。
An additional tip here is appending a /
to the pattern. In the question you specified to get the latest directory. With this trailing /
only directories will be matched, otherwise if a file exists that is the latest and matches the pattern nlb*
that would break your script.
这里的另一个提示是/
在模式后附加 a 。在您指定获取最新目录的问题中。使用此尾随/
仅匹配目录,否则,如果存在最新的文件并且与会nlb*
破坏脚本的模式匹配。
I also changed the `...`
to $(...)
which is the modern recommended writing style.
我也改变了`...`
到$(...)
这是现代推荐的写作风格。