簡體   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