bash - 脚本不显示目录中存在的文件名

标签 bash shell scripting

#!/bin/bash
file=/home/yaal/temp/hatch/*;
if [[ -f  $file ]]; then
 echo $file
else 
echo "No files found"
fi

我的孵化目录下有文件,但它显示“未找到文件”。这是为什么?

谢谢!!

最佳答案

路径名扩展不会发生在非数组变量赋值的右侧,因此 file 包含文字 *,而不是文件名列表。 [[ ... ]] 内部也不执行路径名扩展,因此您询问/home/yaal/temp/hatch 中是否存在名为 * 的文件`.

如果您只想知道hatch中是否至少有一个文件(不包括以.开头的文件),请尝试

for f in /home/yaal/temp/hatch/*; do
    if [[ -f $f ]]; then
        echo "$file"
    else
        echo "No files found"
    fi
    break
done

您还可以填充一个数组,然后检查它是否为空:

files=( /home/yaal/temp/hatch/* )
if (( ${#files[@]} > 0 )); then
    echo "${files[0]}"   # First file found
else
    echo "No files found"
fi

如果您确实想考虑以 . 开头的文件名,请使用 shopt -s dotglob,或使用两种模式 /home/yaal/temp/孵化/*/home/yaal/temp/hatch/.*.

关于bash - 脚本不显示目录中存在的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22644941/

相关文章:

linux - 在 ssh 进入 DC 的时钟服务器后,如何在我的脚本中触发脚本?

Bash:一行的总和字段

bash - 我如何在 bash 中使用 source_once?

bash - 如何向/bin/bash传递参数?

mysql - json 格式的输出数据库大小(来自 Centos7 的 Mariadb)

github - 使用 CLI 从 Github 中的项目获取依赖项

bash : Execute command before redirection as standard input

Bash 命令替换 + 参数扩展

python - 使用 Python 或 shell 脚本更新 XML 文档

delphi - 使用 IScriptControl 创建 JScript 对象