1

I am trying to automate software update with bash script. When I am passing version number e.g 7.16.3 I get following error: ") Syntax error Invalid arithmetic operator (error token is "

I could not find any answer which related when passing value from read command. My code look like below:


DATE=`date +'%Y%m%d'`
BSI_SETUP=/opt/bsi/source/setup/elk_${DATE}
OLD_VERSION_FILEBEAT=`/usr/share/filebeat/bin/filebeat version| awk '{print $3 }' 2>/dev/null`
OLD_VERSION_METRICBEAT=`/usr/share/metricbeat/bin/metricbeat version| awk '{print $3 }' 2>/dev/null`
MY_HOME=~

read -p 'Enter filebeat & metricbeat version: ' NEW_VERSION_BEATS 
read -p 'Enter CSC environmet: ' CSC_ENV

if [[ ${NEW_VERSION_BEATS} -ne ${OLD_VERSION_FILEBEAT} ]]; then # I get error here
   sudo yum install -y $BSI_SETUP/filebeat-*.rpm 2>/dev/null
else
   echo "Filebeat is up-to-date"   
fi

if [[ ${NEW_VERSION_BEATS} -ne ${OLD_VERSION_METRICBEAT} ]]; then # and here 
   sudo yum install -y $BSI_SETUP/metricbeat-*.rpm 2>/dev/null
else
   echo "Metricbeat is up-to-date"      
fi
3
  • 1
    Perhaps you should be using string inequality != instead of numeric inequality -ne in this case? Jan 25, 2022 at 16:04
  • @Quasímodo yes, but how we do call it? Jan 25, 2022 at 16:09
  • @steeldriver I must try it. Thanks for idea! Jan 25, 2022 at 16:10

1 Answer 1

4

-ne does a numeric comparison, while 7.16.3 is not a number. (Even if it's called a "version number".) As it happens, as far as Bash is concerned, neither would 7.16 be, since Bash only deals with integers. The error is actually clearer within Bash's [ .. ]:

$ [ 7.16.3 -ne 7.16.3 ]
bash: [: 7.16.3: integer expression expected

Use [ "$a" = "$b" ], or [[ $a == "$b" ]] for string equality comparison, != for inequality. ([ "$a" == "$b" ] works in Bash, but isn't standard.)

OTOH, if your error really looks like that, with the ") in front, it's due to a carriage return in the value.

$ var=$'7.16\r'
$ [[ $var -ne 7.16 ]]
")syntax error: invalid arithmetic operator (error token is ".16

In that case, check that your input doesn't come from a Windows text file, or use something like var=${var%$'\r'} to remove the CR.

2
  • [ "$a" != "$b" ] also possible? Jan 25, 2022 at 16:13
  • @codehunter-py, yeah, see edit, just realized it was -ne and not -eq there...
    – ilkkachu
    Jan 25, 2022 at 16:14

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .