运行 ls 来自脚本时的不同行为

Different behavior when running ls from within a script

我想重命名几个以枚举方式命名的文件。我以前的方法是使用此命令行:

FILES=`ls "someDir/"`; for f in $FILES; do echo "Processing file: $f"; done;

Echoing 文件名仅用于演示目的。以上产生了预期的输出:

Processing file: File1
Processing file: File2
Processing file: File3
...

然而,当我 运行(我认为是同一件事)下面的脚本时,它将整个 ls 输出视为一个文件并生成此输出:

SCRIPT:
#!/bin/bash
FILES=`ls "someDir/"`

for f in $FILES
do
    echo "Processing file: $f"
done

OUTPUT:
Processing file: File1
File2
File3
...

我无法理解它。此外,我什至不确定是否 ls 产生了这种行为。 是什么导致了这种行为?为什么?

参见 Why you shouldn't parse the output of ls(1), and rather use process-substitution 处理命令输出。

#!/bin/bash

while IFS= read -r -d '' file; do
    echo "$file"
    # Do whatever you want to do with your file here
done < <(find someDir/ -maxdepth 1 -mindepth 1 -type f -print0 | sort -z)

上面的简单 find 列出了所需目录中的所有文件(包括带有 spaces/special-characters 的文件)。此处,find 命令的输出被馈送到 stdin,后者由 while-loop.

解析

要对文件进行有序排序,请将 sort -z 通过管道添加到 find 命令输出。