Interesting ... (I'm not sure where to post the comment ... here or there ... but let's make it here)
Must confess the script is really ugly
(as xzid allready mentioned)
Re the local ip, the line below is much simpler than what you suggest (works on linux, dunno for bsd and sunOS):
hostname -I
In case you have more than one ip, using cut can help to extract only one, e.g.:
# extracts the second ip
hostname -I | cut -d' ' -f2