获取 f=$(cd dir | ls -t | head) 不遵循"dir"的目录中最新文件的路径

  • 本文关键字:dir 路径 文件 最新 cd ls 获取 head bash sh
  • 更新时间 :
  • 英文 :


我想用这部分代码从路径中获取文件(zip文件file=$(cd '/path_to_zip_file' | ls -t | head -1)。相反,我在运行此文件的目录中获得了.sh文件。

为什么我不能从/path_to_zip_file提交

下面是我在.sh文件中的代码

file=$(cd '/path_to_zip_file' | ls -t | head -1)
last_modified=`stat -c "%Y" $file`;
current=`date +%s`
echo $file
if [ $(($current-$last_modified)) -gt 86400 ]; then
echo 'Mail'
else
echo 'No Mail'
fi;

如果你打算使用ls -t | head -1(你不应该使用(,cd需要更正为先前的命令(发生在ls发生之前(,而不是管道组件(ls并行运行,其stdout连接到ls的stdin(:

set -o pipefail # otherwise, a failure of ls is ignored so long as head succeeds
file=$(cd '/path_to_zip_file' && ls -t | head -1)

更好的实践方法可能如下所示:

newest_file() {
local result=$1; shift                      # first, treat our first arg as latest
while (( $# )); do                          # as long as we have more args...
[[ $1 -nt $result ]] && result=$1         # replace "result" if they're newer
shift                                     # then take them off the argument list
done
[[ -e $result || -L $result ]] || return 1  # fail if no file found
printf '%sn' "$result"                     # more reliable than echo
}
newest=$(newest_file /path/to/zip/file/*)
newest=${newest##*/}  ## trim the path to get only the filename
printf 'Newest file is: %sn' "$newest"

要了解${newest##*/}语法,请参阅 bash-hackers 关于参数扩展的 wiki。

有关为什么在脚本中使用ls(显示给人类的输出除外(是危险的,请参阅解析L。

Bot BashFAQ #99,如何从目录中获取最新(或最旧(文件?-- 和 BashFAQ #3(如何根据某些元数据属性(最新/最旧的修改时间、大小等(对文件进行排序或比较?(对提出这个问题的更大背景进行了有益的讨论。

最新更新