检查文件是否存在于不同目录中的多个文件

时间:2020-01-27 21:39:56

标签: bash

我正在创建bash脚本,除此以外,一切正常:

read -p "Write directory names:" -a dir
for f in /home/user/downloads/${dir[@]}/*.zip; do
    if [ -f $f ]; then
        #do something
    else 
        #do something else
    fi
done

我想检查目录中是否存在.zip文件;多个目录一个接一个地

1 个答案:

答案 0 :(得分:2)

您不能将数组替换为文件名,而需要遍历数组。

read -p "Write directory names:" -a dirs
for dir in "${dirs[@]}"; do
    for f in "/home/user/downloads/$dir/"*.zip; do
        if [ -f "$f" ]
        then
            # do something
        else
            # do something else
        fi
    done
done

如果您只想测试通配符是否与每个目录中的任何内容匹配,请使用以下一种解决方案替换内部循环:Test whether a glob has any matches in bash