簡體   English   中英

帶有空格且元素中沒有空格的 Bash 數組

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM