簡體   English   中英

為什么我的 bash 腳本中不斷出現語法錯誤? 它是否與“:”有關?

[英]Why do I keep getting syntax error in my bash script? Does it have something related to the “:”?

我正在嘗試計算 errorList 數組中每個項目的錯誤,但我不斷收到“表達式中的語法錯誤(錯誤標記是“:只是一個測試”)”。

#!/bin/bash

declare -a errorList=(
    'MEDIA ERROR: just a test'
    'MEDIA BLA: resource unavaliable!'
    'DIALOG: Found PROBLEM ev_id="EV_ID"'
    )

declare -a errorListNames=(
    "Silence"
    "Unavaliable"
    "Environment error"
    )

pathLogs="/home/logs_test/"
logFileName="media.log.*"

dateLog="10-10-2019"

fgrep "$dateLog" $pathLogs$logFileName > grepedByDate.txt

for i in "${errorList[@]}"
    do
        fgrep -c "${ errorList[i], }" grepedByDate.txt
        echo "${errorListNames[i]}"
    done

echo "Bye"

1.使用! #獲取密鑰

代替:

for i in "${errorList[@]}"

利用:

for i in ${!errorList[@]}"

或者:

maxIndex=${#errorList[@]}
for (( i=0; i<$maxIndex; i++ ))

2. 空格在變量引用中很重要

代替:

        fgrep -c "${ errorList[i], }" grepedByDate.txt

利用:

        fgrep -c "${errorList[i]}" grepedByDate.txt

您可以使用關聯數組:

#!/usr/bin/env bash

declare -A errors=(
    [Unavailable]='MEDIA ERROR: Resource unavailable'
)

for i in "${!errors[@]}"; do
    echo "$i: ${errors[$i]}"
done  
  • ${!errors[@]}擴展為鍵( Unavailable ,...)並存儲在$i
  • ${errors[$i]}擴展為給定鍵$i的值( MEDIA ERROR... ,...)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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