繁体   English   中英

比较文件名和字符串时,bash脚本显示“无此文件或目录”

[英]bash script prints “No such file or directory” when comparing filenames to string

我正在检查是否希望与同名文件创建冲突的文件。

FILEPATH=/root/logs/pData*.csv
COMPPATH=/root/logs/pData*.csv.gz
shopt -s nullglob
thisYear="$(date +"%Y")"
thisMonth="$(date +"%m")"
thisDay="$(date +"%d")"
thisTime="$(date | cut -d ' ' -f 4 | tr : _)"

for file in $FILEPATH
do
    fileYear="$(stat -c %y $file | cut -d'-' -f 1)"
    fileMonth="$(stat -c %y $file | cut -d'-' -f 2)"
    fileDay="$(stat -c %y $file | cut -d'-' -f 3 | cut -d' ' -f 1)"
    fileTime="$(stat -c %y $file | cut -d ' ' -f 2 | cut -d '.' -f 1 | tr : _)"

    if (("$fileYear" < '1990'))
            then
                    fName="pData_"$thisYear"_"$thisMonth"_"$thisDay"_"$thisTime".csv.gz"
            else
                    fName="pData_"$fileYear"_"$fileMonth"_"$fileDay"_"$fileTime".csv.gz"
    fi

    echo $fName

    for file in $COMPPATH
    do
            if ('/root/logs/'$fName == $file)
                    then
                            echo "OOPS"
            fi
    done
done

该脚本在大多数情况下均按预期工作,当我遇到同名文件时打印OOPS,但对于不存在的文件,它会打印

./compress.sh: line 31: /root/logs/pData_2015_09_18_22_25_44.csv.gz: No such file or directory

为什么要打印?

如何防止这种情况发生?

字符串比较是错误的。 使用单括号创建一个子外壳并尝试执行'/ root / logs /'$ fName

设置您的字符串比较为:

if [[ '/root/logs/'$fName = $file ]]

请参阅: http : //www.tldp.org/LDP/abs/html/comparison-ops.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM