mardi 18 août 2020

Getting an error for unexpected else in bash

[SOLVED] I'm pretty new tho bash-/shell-scripting and trying setup a check for ip address on a server which gets about once a week a new ip. The script will then send the new ip to the users.

My problem is, that I'm getting a syntax-error in the last if-else statement for "unexpected" else and can wrap my head around why.

My first iteration didn't use functions, but instead one multi lined if-else which got me the same error. The functions on their own seem to work just fine.

#!/bin/bash

# script to send the new server ip to the users

# get the recent ip address of the system
new_ip=$(ip route get 8.8.8.8 | awk -F"src " 'NR==1{split($2,a," ");print a[1]}')

file=old_ip.txt

function ip_mail(){
 source $file
 if [ $new_ip != $old_ip ]
  then
  # email-address changed for obvious reasons
  mail -s "New Server IP" [hidden]@[hidden].com <<< "$new_ip"
  echo "old_ip=$new_ip" > old_ip.txt
  exit 0
  fi
    
    exit 0
}

function set_old(){
 touch old_ip.txt
 echo "old_ip=$new_ip" > old_ip.txt
 exit 0
}

if [ $file ]
then
 ip_mail()
else
 set_old()
fi

Aucun commentaire:

Enregistrer un commentaire