ls对于这项工作不是一个可靠的工具:它不能代表所有可能的文件名(空格是可能的,但也包括换行符和其他特殊字符 - 除NUL以外)。与GNU工具系统上的一个健壮的解决方案是使用find:
{
# read the first size and name
IFS= read -r -d' ' first_size; IFS= read -r -d '' first_name;
# handle case where only one file exists
last_size=$first_size; last_name=$first_name
# continue reading "last" size and name, until one really is last
while IFS= read -r -d' ' curr_size && IFS= read -r -d '' curr_name; do
last_size=$curr_size; last_name=$curr_name
done
} <
上面放结果到变量$first_size,$first_name,$last_size和$last_name,可用正是如此:
printf 'Smallest file is %d bytes, named %q\n' "$first_size" "$first_name"
printf 'Largest file is %d bytes, named %q\n' "$last_size" "$last_name"
在术语它是如何工作的:
find ... -printf '%s %P\0'
...从find发出以下形式的流:
通过sort -n -z运行该流并对其内容的数字排序。 IFS= read -r -d' ' first_size读取第一个空间的所有内容; IFS= read -r -d '' first_name读取所有内容,直到第一个NUL;然后循环继续读取并存储其他大小/名称对,直到到达最后一个。