简体   繁体   中英

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

I'm trying to count the errors for each item in my errorList array, but I keep getting the "syntax error in expression (error token is ": just a test")".

#!/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. Use ! or # to obtain keys

Instead of:

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

use:

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

or:

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

2. Whitespace is significant inside variable references

Instead of:

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

use:

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

You could use an associative array:

#!/usr/bin/env bash

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

for i in "${!errors[@]}"; do
    echo "$i: ${errors[$i]}"
done  
  • ${!errors[@]} expands to keys ( Unavailable , ...) and is stored in $i
  • ${errors[$i]} expands to values for the given key $i ( MEDIA ERROR... , ...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM