Home > linux > bash scripting: change delim using for

bash scripting: change delim using for

gennaio 7, 2013

Usually when I write shell script I prefer to use the statement “for”.
But there’s a problem: by default the ‘for’ get every single word.

That’s because if not specified the ‘for’ use as delimiter the space character (” “).
So, if I want to work with several word in a single iteration i need to change the delimiter.

That’s easy!
To change the delimiter you just need to change the variable IFS.

Let’s see some code:


LOGFILE=/var/log/mylogfile.log
IFS=";"                              # change delimiter in ";" (magic)
EXCEPTIONS="timeout;java.somerror;a lot of errors"    # my exception 
for word in $EXCEPTIONS;do
    echo -n "Check Exception: \"$word\" ..."         # escape "
    N=$(grep -ic $word $LOGFILE)                     # check log
    if [ $N -gt 0 ];then                             # if found
        echo -e "\nWARNING: Found $N exception:\"$word\"" # print 
    else
        echo "None"                                  # else no
    fi
done

output:


> Check Exception: "timeout"...None
> Check Exception: "java.somerror"...None
> Check Exception: "a lot of errors"...
WARNING: Found 3 exception "a lot of errors"

That’s an easy way to use the ‘for’ statement even if usually cant and so you can write good code.
enjoy🙂

Categorie:linux Tag:, , , , , , ,