[英]bash script prints “No such file or directory” when comparing filenames to string
I am checking to see if a file I am hoping to create conflicts with a file that has the same name. 我正在检查是否希望与同名文件创建冲突的文件。
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
The script works as intended for the most part, printing OOPS when I run into a file of the same name, but for files that don't exist it prints 该脚本在大多数情况下均按预期工作,当我遇到同名文件时打印OOPS,但对于不存在的文件,它会打印
./compress.sh: line 31: /root/logs/pData_2015_09_18_22_25_44.csv.gz: No such file or directory
Why is this printed? 为什么要打印?
How do I prevent this from happening? 如何防止这种情况发生?
The string comparison is wrong. 字符串比较是错误的。 Using single parentheses is creating a sub-shell and trying to execute '/root/logs/'$fName
使用单括号创建一个子外壳并尝试执行'/ root / logs /'$ fName
Set your string compare to be: 设置您的字符串比较为:
if [[ '/root/logs/'$fName = $file ]]
See: http://www.tldp.org/LDP/abs/html/comparison-ops.html 请参阅: http : //www.tldp.org/LDP/abs/html/comparison-ops.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.