Bash: if语句没有看到循环抓取的文件名

Bash: If statement does not see the filename grab by loop

我正在努力学习 bash 并且我做了一个这样的班轮:

for f in *; do echo $f; done

这将打印当前目录中的所有文件名。

输出:

a file
testfile

既然f能抓到"a file"就好了,那我就这么干:

for f in *; do
    if [ -f ${f} ]; then
       LINE=$(wc -l < $f)
       WORD=$(wc -c < $f)
       echo $f ${LINE} ${WORD}
    fi
done

此脚本在第 4 行失败,因为 "a file" 中有 space。

我需要帮助:为什么会失败?

F 能够正确获取文件名。直觉上,我相信 -f ${f} 能够检查 "a file" 是否是一个文件。

为什么 "a file" 通过了 for 循环但在 if 语句检查时失败了?

您需要(双)引用 $f 的每个引用,以便 bash 知道 'a' 和 'file' 不是单独的对象,例如:

for f in *; do
    if [ -f "${f}" ]; then
       LINE=$(wc -l < "${f}")
       WORD=$(wc -c < "${f}")
       echo "${f}" ${LINE} ${WORD}
    fi
done