将Bash脚本cd到目录中的最新目录中 [英] Bash script to cd into newest directory within a directory
问题描述
我正在尝试向正在编写的数据收集bash脚本中添加功能。目的是指向一个特定的目录,然后在父目录中cd到最新目录。
I am trying to add a function to a data collection bash script I am writing. The intention would be to point to a specific directory, and then cd into the NEWEST directory within the parents.
伪代码:
cd top_dir
for each dir in top_dir:
age = dir.age
if age < least_age:
least_age = age
newest_dir = dir
cd newest_dir
我尝试使用 cd $(find $ 1 / * -prune -type d 2> / dev / null | xargs stat -c%Y%n 2> / dev / null |排序-nr |头-n 1 |从 -to-newest-directory>此帖子,但是cd将我引导到计算机上的最新目录中。
I have tried using cd "$( find "$1"/* -prune -type d 2>/dev/null | xargs stat -c "%Y %n" 2>/dev/null | sort -nr | head -n 1 | cut -d " " -f 2-)"
from this post, but that instead cd's me into the newest directory on my computer.
本意是用于目录
parent_dir:
child_1 | Last Edited 1 Hr Ago
child_2 | Last Edited 1 Yr Ago
child_3 | Last Edited 2 Yr Ago
child_4 | Last Edited 1 Min Ago
child_5 | Last Edited 1 Week Ago
该命令将 cd
将我导入 child_4
推荐答案
您要使用的代码是旨在成为功能的主体;正确调用函数集 $ 1
。就其本身而言,可能未设置 $ 1
,因此在 /上的
(与查找
运算符 /
相同),而不是 top_dir
。
The code you are trying to use is intended to be the body of a function; calling the function sets $1
properly. By itself, $1
probably isn't set, and so find
operators on ""/
(same as /
), not top_dir
.
new_cd () {
cd "$( find "$1"/* -prune -type d 2>/dev/null | xargs stat -c "%Y %n" 2>/dev/null | sort -nr | head -n 1 | cut -d " " -f 2-)"
}
new_cd top_dir
这可以简化一些。无需使用 find
或 xargs
;一个简单的循环就可以了。而且,既然您现在有了函数,就无需将所有内容都塞进一行。
This can be simplified a little. There's no need to use find
or xargs
; a simple loop will do. And since you have a function now, there's no need to cram everything in one line.
new_cd () {
new_d=$(for d in "$1"/*/; do
stat -c "%Y %n" "$d" 2> /dev/null
done | sort -nr |
head -n |
cut -d " " -f 2-)
cd "$new_d"
}
这有一个小缺点:命令替换将在 cut
的输出中吃掉所有尾随的换行符,因此请确保没有您的目录名称以换行符结尾。 (可以修复此极其微小的错误,但可能不值得这样做;仅需注意即可。)
This has one minor drawback: the command substitution will eat any trailing newlines in the output of cut
, so make sure none of your directory names ends with a newline character. (This extremely minor bug can be fixed, but it probably isn't worth doing so; just be aware of it.)
它还有一个更大的缺点: em> non 跟踪的换行符没有被吃掉了,您不能假设循环的输出每行只包含一个文件。一个文件可以占用多行。最简单的解决方法是避免使用换行符的目录名称。
It also has a bigger drawback: since non-trailing newlines aren't eaten, you cannot assume the output of the loop consists of exactly one file per line; a single file could occupy multiple lines. The easiest fix is to avoid directory names with newlines. A more robust fix abandons the pipeline.
new_cd () {
local newest_time newest_d
for d in "$1"/*/; do
t=$(stat -c "%Y" "$d")
if (( t > newest_time )); then
newest_time=$t
newest_d=$d
fi
done
cd "$newest_d"
}
这篇关于将Bash脚本cd到目录中的最新目录中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!