在 bash 脚本中如何遍历按日期排序的文件

Chi*_*wda 2 sorting bash

我有以下脚本:

#!/bin/sh
HOST='host'
USER='user@example.com'
PASSWD='pwd'

for FILE in *.avi
do
    ftp -n $HOST <<END_SCRIPT
    quote USER $USER
    quote PASS $PASSWD
    binary
    put $FILE
    rm FILE 
    quit
done
END_SCRIPT
exit 0
Run Code Online (Sandbox Code Playgroud)

如何确保首先处理最旧的文件?我见过很多使用 ls -t 的 hack,但必须有更简单的方法。

mju*_*rez 6

我会for用这个修改你的循环:

for FILE in `ls -tU *.avi`
do
  #
  # loop content here with ${FILE}
  #
done
Run Code Online (Sandbox Code Playgroud)

ls文档:

-t      Sort by time modified (most recently modified first) before 
        sorting the operands by lexicographical order.
-U      Use time of file creation, instead of last modification for 
        sorting (-t) or long output (-l).
Run Code Online (Sandbox Code Playgroud)

  • 是的,它涵盖了您不应该以及其他方式来迭代文件列表,但不包括如何迭代文件列表*按日期排序*,这是这个问题的核心。您对此有什么建议吗? (7认同)
  • 违反第 1 号陷阱将永远让你失望...... ***永远不要***在 $(ls 任何东西) 中使用 `for i`,请参阅 [**Bash Pitfalls #1**](http://mywiki) .wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29) -- 他们称之为 **Pitfall No. 1** 是有原因的。 (6认同)
  • 虽然您可能已经弄清楚了,但为了满足首先按最旧的文件排序的要求,请使用 -tr (按时间倒序排序)。 (2认同)