Mtr
Mtr

Reputation: 27

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"

Upvotes: 0

Views: 348

Answers (2)

mickp
mickp

Reputation: 1809

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..., ...)

Upvotes: 1

jhnc
jhnc

Reputation: 16817

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

Upvotes: 1

Related Questions