Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read string and convert to INT (BASH)

I have a simple script in Bash to read a number in a file and then compare it with a different threshold. The output is this:

: integer expression expected
: integer expression expected
OK: 3

My code is this:

#!/bin/bash

wget=$(wget http://10.228.28.8/ -O /tmp/wget.txt 2>/dev/null)
output=$(cat /tmp/wget.txt | awk 'NR==6')
#output=7
echo $output

if [ $output -ge 11 ];then
    echo "CRITICAL: $output"
    exit 2
elif [ $output -ge 6 ] && [ $output -lt 11 ];then
    echo "WARNING: $output"
    exit 1
else
    echo "OK: $output"
    exit 0
fi

rm /tmp/wget.txt

I know what is the problem, I know that I'm reading a string and I try to compare a int. But I don't know how can I do to read this file and convert the number to read in a int var..

Any ideas?


2 Answers

The problem occurs when $output is the empty string; whether or not you quote the expansion (and you should), you'll get the integer expression required error. You need to handle the empty string explictly, with a default value of zero (or whatever default makes sense).

wget=$(wget http://10.228.28.8/ -O /tmp/wget.txt 2>/dev/null)
output=$(awk 'NR==6' < /tmp/get.txt)
output=${output:-0}

if [ "$output" -ge 11 ];then
  echo "CRITICAL: $output"
  exit 2
elif [ "$output" -ge 6 ];then
  echo "WARNING: $output"
  exit 1
else
  echo "OK: $output"
  exit 0
fi

(If you reach the elif, you already know the value of $output is less than 11; there's no need to check again.)


The problem also occurs, and is consistent with the error message, if output ends with a carriage return. You can remove that with

output=${output%$'\r'}
like image 126
chepner Avatar answered Sep 13 '26 06:09

chepner


There are a couple of suggestions from my side regarding your code.

You could explicitly tell bash the output is an integer

declare -i output # See [1]

Change

output=$(cat /tmp/wget.txt | awk 'NR==6') # See [2]

may be better written as

output=$(awk 'NR==6' /tmp/wget.txt )

Change

if [ $output -ge 11 ]

to

if [ "0$output" -ge 11 ] # See [4]

or

if (( output >= 11 )) # Better See [3]

References

  1. Check bash [ declare ].
  2. Useless use of cat. Check [ this ]
  3. Quoting [ this ] answer :

    ((...)) enable you to omit the dollar signs on integer and array variables and include spaces around operators for readability. Also empty variable automatically defaults to 0 in such a statement.

  4. The zero in the beginning of "0$output" help you deal with empty $output

Interesting
Useless use of cat is a phrase that has been resounding in SO for long. Check [ this ]
[ @chepner ] has dealt with the empty output fiasco using [ bash parameter expansion ] in his [ answer ], worth having a look at.

like image 27
sjsam Avatar answered Sep 13 '26 07:09

sjsam