linux - 使用 ls -f 过滤文件输出

标签 linux bash

我正在尝试编写一个 bash 脚本来检查文件是否是有效文件。 这是我正在使用的代码。

echo "Select your file"
read $TEST_FILE

for file in `ls $TEST_FILE`; do
    if [ -f $TEST_FILE ]; then
        echo "$TEST_FILE is a regular file" 
    fi
done

但我得到的结果是这样的。

 is a regular file
 is a regular file
 is a regular file
 is a regular file
 is a regular file

当我只指定一个特定的文件时,它会列出目录中的所有文件。我希望它能够仅针对该 1 个文件吐出结果..

我该怎么做?

谢谢!

最佳答案

首先,您在 read 中错误地使用了变量 - 不要使用 $ - 您只在 referring 时使用 $到变量的现有值,而不是在分配一个值时;相反:

echo "Select your file"
read TEST_FILE

如果假设 $TEST_FILE 是一个单一的文字文件名,那么您根本不需要 for 循环:

if [[ -f $TEST_FILE ]]; then
    echo "$TEST_FILE is a regular file" 
fi

如果假设 $TEST 是一个文件名 pattern,则如下:

for f in $TEST_FILE; do
    if [[ -f $f ]]; then
        echo "$f is a regular file" 
    fi
done

请注意,我使用的是更健壮和灵活的 [[...]] 而不是 [...] 测试结构。

事后的想法

OP 提到了 ls-f 标志,这导致(可能取决于文件系统)未排序 输出也 < em>包括以 开头的条目。

相比之下,带有 glob(文件名模式)的 for 循环总是扩展到已排序 条目(据我观察)。 此外,要使 glob 匹配以 . 开头的条目,必须设置 dotglob shell 选项 (shopt -s dotglob)。

关于linux - 使用 ls -f 过滤文件输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21659837/

相关文章:

linux - 如何故意将 Linux 中的可用内存减少给定量?

mysql脚本bash循环

linux - 使用 sed "s| ACT: ||"

linux - eclipse : impossible to import git project

linux - 无法通过 linux 命令向 office 365 发送电子邮件

java - CORB 作业 : Handle ServerConnectionException: Connection reset by peer

mysql - 从 CSV 文件中删除字符

linux - 不扩展 $HOME 或 "~"的符号链接(symbolic link)?

php - xDebug 没有在断点处停止

c++ - 当我从 C++ 程序调用脚本时出现语法错误