In a bash script how to loop through files sorted by date

我的梦境 提交于 2020-12-04 04:37:47

问题


I have the following script:

#!/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

How do I ensure that I process the oldest file first? I have seen a lot of hacks that use ls -t, but there has to be a simpler way.


回答1:


I would modify your for loop with this:

for FILE in `ls -tU *.avi`
do
  #
  # loop content here with ${FILE}
  #
done

From the ls docs:

-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).


来源:https://stackoverflow.com/questions/55233180/in-a-bash-script-how-to-loop-through-files-sorted-by-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!