[英]Bash array with spaces and no spaces in elements
我知道这个问题以不同的方式被问到,我已经参考了这里的一些答案来了解我现在的情况。
我正在尝试创建一个脚本,以便在没有写入文件夹和病毒扫描文件时对其进行基本监视。
我需要它处理的文件/字符串有时包含空格,有时不包含,有时也包含特殊字符。 目前,它实际上仅适用于名称中有空格的文件(如实际扫描和移动它们),但不适用于没有空格的文件。 同样在每个文件(空格与否)之后,while 循环会中断,从而使用以下输出停止脚本;
./howscan.sh: line 29: snmp.conf: syntax error: invalid arithmetic operator (error token is ".conf")
./howscan.sh: line 34: snmp.conf: syntax error: invalid arithmetic operator (error token is ".conf")
我让它处理没有任何空格的文件名,但是由于我引入了"${files[$i]}"
方法来使用数组元素,它只适用于带有空格的文件并输出上述错误。
随意省略其中的 sepscan 部分,因为我确定我是否可以让它与其他任务一起工作(只是想显示完整的脚本以获得完整的理解)。
当前脚本:
#!/bin/bash
set -x
workingpath='/mnt/Incoming/ToScan/'
outputpath='/mnt/Incoming/Scanned/'
logfile='/var/log/howscan.log'
faildir='/mnt/Incoming/ScanFailed/'
sepscan='/opt/Symantec/symantec_antivirus/sav manualscan -c'
# Change to working directory
cd $workingpath
# Exclude files with a given extension, in this case .aspx, and declare the remaining files as the array "files"
shopt -s extglob nullglob
# Loop the below - ie it's a watch folder
while true
do
# Exclude files with .aspx in the file name
files=( !(*.aspx) )
# If the array files is not empty then...
if [ ${#files[@]} -ne 0 ]; then
for i in ${files[*]}
# For every item in the array files process them as follows
# Declare any variables you wish to happen on files here, not globally
# Check each file to see if it's in use using fuser, do nothing and log it if its still in use, or process it and log the results
do
fileopen=`fuser "${files[$i]}" | wc -c`
# Here for 'fileopen' we are checking if the file is being writen to.
if [ $fileopen -ne 0 ]; then
echo `date` "${files[$i]}" is being used so has been ignored >> $logfile
else
echo `date` File "${files[$i]}" not being used or accessed >> $logfile
sepscan=`$sepscan "${files[$i]}" | wc -c`
if [ $sepscan = 0 ]; then
mv "${files[$i]}" $outputpath
echo `date` "${files[$i]}" has been virus scanned and moved to $outputpath >> $logfile
else
echo `date` "${files[$i]}" has been moved to $faildir as a virus or error was detected >> $logfile
fi
fi
done
fi
echo `date` 'No more files to process. Waiting 60 seconds...' >> $logfile
sleep 60
done
如果我能提供任何其他信息来帮助澄清我的问题,请告诉我。
更新:
顺便说一下,/mnt/Incoming/ToScan/ 目录下有个文件叫snmp.conf。
for i in ${files[*]}
应该
for i in ${!files[*]}
# or
for i in ${!files[@]}
${files[*]}
扩展为数组的内容并进行分词。 上面的语法扩展为数组的索引列表。
您可能还需要双引号变量,例如
if [ "$fileopen" -ne 0 ]; then
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.