如何以可靠和可移植的方式迭代目录中的文件,最早的?

时间:2017-06-02 22:54:04

标签: linux shell scripting posix busybox

“健壮” - 我正在尝试处理文件名中包含空格和换行符以及其他特殊字符的文件 - 只是因为我看到了一些特殊字符,尽管被告知我的目标环境不会有它们。

“Portably” - 需要在各种Linux机器上运行,包括BusyBox。

“Oldest” - 通过修改时间,将名字作为决胜局就足以达到我的目的。

通常我会使用find -type f -printf '%T+ %p\n' 2>/dev/null | sort | cut -d' ' -f2 | while read filename; do mything "$filename"; done

但是在这个特殊的BusyBox v1.18.4上find不支持-printf所以我不确定我是否可以使用find来公开修改修改时间。

Usage: find [PATH]... [EXPRESSION]

Search for files. The default PATH is the current directory,
default EXPRESSION is '-print'

EXPRESSION may consist of:
-follow     Follow symlinks
-xdev       Don't descend directories on other filesystems
-maxdepth N Descend at most N levels. -maxdepth 0 applies
        tests/actions to command line arguments only
-mindepth N Don't act on first N levels
-name PATTERN   File name (w/o directory name) matches PATTERN
-iname PATTERN  Case insensitive -name
-path PATTERN   Path matches PATTERN
-regex PATTERN  Path matches regex PATTERN
-type X     File type is X (X is one of: f,d,l,b,c,...)
-perm NNN   Permissions match any of (+NNN), all of (-NNN),
        or exactly NNN
-mtime DAYS Modified time is greater than (+N), less than (-N),
        or exactly N days
-mmin MINS  Modified time is greater than (+N), less than (-N),
        or exactly N minutes
-newer FILE Modified time is more recent than FILE's
-inum N     File has inode number N
-user NAME  File is owned by user NAME (numeric user ID allowed)
-group NAME File belongs to group NAME (numeric group ID allowed)
-depth      Process directory name after traversing it
-size N[bck]    File size is N (c:bytes,k:kbytes,b:512 bytes(def.))
        +/-N: file size is bigger/smaller than N
-links N    Number of links is greater than (+N), less than (-N),
        or exactly N
-print      Print (default and assumed)
-print0     Delimit output with null characters rather than
        newlines
-exec CMD ARG ; Run CMD with all instances of {} replaced by the
        matching files
-prune      Stop traversing current subtree
-delete     Delete files, turns on -depth option
(EXPR)      Group an expression

我读到循环ls的输出是一个坏主意。

我的环境也不支持stat -c format,但我可以使用stat -t ...

所以我目前的想法是

cd "$1"

if [ $? -ne 0 ]; then
    printf 'failed cd'
    exit 1
fi

while read name
do
    mything "$name"
done <<< "$(stat -t ./*                \
    | awk -F' ' '{print $13 " " $1}' \
    | sort -r                        \
    | awk -F' ' '{print $2}')"

有更好的方法吗?我依靠stat的'简洁'格式保持一致。

0 个答案:

没有答案