Ayushya
Ayushya

Reputation: 10447

Comparing two numeric variables in Linux

I have declared two numeric variables but am unable to compare them

  remote_file_size=$(curl -sI $URL | grep -i content-length | awk '{print $2}')
  local_file_size=$(ls -l $file_location | awk '{print $5}')

  if [ "$local_file_size" -eq "$remote_file_size" ]; then
      echo "Database up to date. Update not required"
  else
      echo "Database needs to be updated! Downloading newer version"
      wget --continue -O $file_location $URL
  fi

I've also tried,

 if [[ "$local_file_size"="$remote_file_size" ]];
 if [[ "$local_file_size"=="$remote_file_size" ]];
 if [[ $local_file_size==$remote_file_size ]];
 if [[ $local_file_size == $remote_file_size ]];

Upvotes: 2

Views: 373

Answers (2)

that other guy
that other guy

Reputation: 123680

curl is notorious for outputting invisible but harmful carriage returns directly from HTTP responses. This is why you're getting this weird, wrapped message:

")syntax error: invalid arithmetic operator (error token is "

You can strip them with tr:

#                                  v-- Here
remote_file_size=$(curl -sI $URL | tr -d '\r' | grep -i content-length | awk '{print $2}')

Upvotes: 2

bishop
bishop

Reputation: 39474

You may find typesetting the variables as integers to be helpful:

$ typeset -i a="123"
$ typeset -i b="242"
$ [ $a -lt $b ] && echo 'a < b' || echo 'a >= b'
a < b
$ a=545
$ [ $a -lt $b ] && echo 'a < b' || echo 'a >= b'
a >= b

Upvotes: 1

Related Questions