2

I have the below script in my system:

#!/bin/sh

LASTFILES=`find /var/log -mtime -1 -iname *.csv`

KEYWORDS="MD AG GA"

countMD="0"
countAG="0"
countGA="0"

for i in $LASTFILES ; do
    for a in $KEYWORDS ; do
        count_$a=`grep -a $date $i | grep -i "\"$a\"" | grep smsMoBilling | wc -l`
        count$a=`expr $count$a + $count_$a`
         done
done

It doesn't work when I run it.

./test.sh: line 35: count_MD=37: command not found
expr: non-numeric argument
./test.sh: line 36: countMD=: command not found

What is the matter with the variable declared? Could you help me?

2
  • Your listing is incomplete. Line 35 is beyond that loop.
    – ott--
    Sep 17 '13 at 17:58
  • That, and the first error quotes count_MD while you have countMD in your code.
    – schaiba
    Sep 17 '13 at 18:01
2
count_$a=`grep -a $date $i | grep -i "\"$a\"" | grep smsMoBilling | wc -l`

There's a syntax error here. In an assignment, you need to put a variable name before the =. A longer piece of text that expands to a variable name isn't supported.

Instead of generating variable names from pieces, use associative arrays indexed by the variable part. This requires a shell that supports associative arrays: ksh93, bash or zsh. While you're at it, don't parse the output of find (it might work here, but it doesn't work in general when file names may contain whitespace or \[*?). Use shell globbing and arrays instead.

#!/bin/bash
shopt -s globstar
CSV_FILES=(/var/log/**/*.[Cc][Ss][Vv])
KEYWORDS=(MD AG GA)
typeset -A count
for i in "${CSV_FILES[@]}" ; do
    for a in "${KEYWORDS[@]}" ; do
        count[$a]+=$(grep -a "$date" "$i" | grep -i "\"$a\"" | grep smsMoBilling | wc -l)
    done
done
0

Your basic problem here is quoting. Also, I would use an associative array (and bash instead of sh) instead of trying to concatenate the variable names (that might be possible but I haven't been able to get it to work). The details of your errors probably depend on the specific file names you have but try this instead:

#!/bin/env bash

LASTFILES=`find /var/log -mtime -1 -iname "*.csv"`

KEYWORDS="MD AG GA"

countMD="0"
countAG="0"
countGA="0"
declare -A count1;
declare -A count2;

for i in "$LASTFILES" ; do
    for a in "$KEYWORDS" ; do
         count1[$a]=`grep -a "$date" "$i" | grep -i "\"$a\"" | grep -c smsMoBilling`
         count2[$a]=$((${count2[$a]}+${count1[$a]}));
    done
done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.