我正在为 shell 脚本中的文件验证工作,我们需要从 tar 文件中读取文件大小和文件名并验证文件大小是否大于特定大小,并且 tar 文件还包含所有强制性文件列表。
下面是我写的代码,有什么方法可以一次循环检查文件名和文件大小。
任何意见都值得赞赏。提前感谢...
#!/bin/bash
minimumsize=90000
mandatoryFiles=(party.dat test1.dat test2.dat)
ALL_FILE_NAMES=`tar -tvf testData/test_daily.tgz | awk '{print $6}' ` #get file names in tar file
ALL_FILE_SIZES=`tar -tvf testData/test_daily.tgz | awk '{print $3}' ` #get file sizez in bytes
echo "File names :::::::::::"$ALL_FILE_NAMES
echo "File sizes :::::::::::"$ALL_FILE_SIZES
#condition to check file size is greater than minimum size
for actualsize in $ALL_FILE_SIZES; do
if [ $actualsize -ge $minimumsize ]; then
echo size is over $minimumsize bytes
else
echo size is under $minimumsize bytes
exit 0
fi
done
#condition to check all the mandatory files are included in the taz file.
for afile in $ALL_FILE_NAMES; do
if [[ ${mandatoryFiles[*]} =~ $afile ]]; then
echo $afile is present
else
echo $afile not present so existing the bash
exit 0
fi
done
你的方法有点尴尬。您只需要捕获所有文件名以循环访问必需文件,但您无法按照当前方式进行检查,否则存档中的任何其他文件(强制文件之外(都会导致测试失败。
一种更简洁的方法是使用进程替换将大小和文件名提供给循环,允许您测试每个文件大小(任何小于 minimumsize
的文件都会导致存档失败(,同时填充all_names
数组。此时,您已完成读取循环。
最后一个循环all_names
检查它们是否存在于mandatoryFiles
中,并增加计数器将允许您检查是否与每个mandatoryFiles
匹配。
一种方法是:
#!/bin/bash
fname="${1:-testData/test_daily.tgz}" ## filename to read
minimumsize=90000 ## min size
mandatoryFiles=(party.dat test1.dat test2.dat) ## mandatory files
declare -a all_names ## all_names array
declare -i mandatory_count=0; ## mandatory count
while read -r size name; do ## read/compare sizes, fill array
all_names+=( "${name##*/}" ); ## store each file name in array w/o path
#condition to check file size is greater than minimum size
if [ "$size" -ge $minimumsize ]; then
echo "$size is over $minimumsize bytes"
else
echo "$size is under $minimumsize bytes"
exit 0
fi
done < <(tar -tzvf "$fname" | awk '{print $3, $6}')
#condition to check all the mandatory files are included in the taz file.
for afile in "${all_names[@]}"; do
if [[ ${mandatoryFiles[@]} =~ "$afile" ]]; then
((mandatory_count++)) ## increment mandatory_count
fi
done
## test if mandatory_count less than number of mandatory files
if [ "$mandatory_count" -lt "${#mandatoryFiles[@]}" ]; then
echo "mandatoryFiles not present - exiting"
exit 1
fi
echo "all files good"
(注意:如果文件是.tgz
(G压缩tar存档(,则需要如上所述添加'z'
选项(
仔细查看,如果您有其他问题,请告诉我。