I need to validate script so error messages are returned

My code cycles through several enviroments looking for a first/last name combination. If that is found it will print out the user_id. If not 'NO USER FOUND' is output.

I have a third issue that I have to check for, and am not quite sure how to do this. If for some reason the connection to the database fails, I need to produce a message like "DATABASE CONNECTION FAILED"

echo "environment"
sshpass -p $ldappw ssh $ldapuser@12.345.678.901  'mysql --skip-column-names -h host -u user -ppassword database -e "select user_id from users where first like '"'%${first_name}%' and last like '%${last_name}%';"'"' >$out_file 
sql_string=$(cat $out_file)
if [[ ! -z $sql_string ]]; then
   echo "$sql_string"
else
   echo "NO USER FOUND"
fi

Open in new window

TampaJayAsked:
Who is Participating?
 
woolmilkporcConnect With a Mentor Commented:
Why didn't you use my suggestion from our previous thread? Are you a big fan of temporary files?

Anyway, change my solution from the previous thread to

#log it all
{
if UID=$(sshpass -p $ldappw ssh $ldapuser@12.345.67.89 'mysql --skip-column-names -hhost -u user -ppassword database -e \
"select user_id from users where first like '"'%${first_name}%' and last like '%${last_name}%';"'"')
then
   if [[ ! -z $UID ]]; then
      echo "environment"
      echo "$UID"
        else
           echo "NO USER FOUND"
   fi
else
  echo  "DATABASE CONNECTION FAILED"
fi 
} > $log

Open in new window


You can take out "echo "environment"" and put it above the line containing "sshpass" as in your question, if you like, yet this would somehow contradict what we discussed in that famous previous thread.
0
 
TampaJayAuthor Commented:
I  must have missed that first time around. Sorry about that.

Thanks for the help with these few problems - been a great assistance!
0
 
TampaJayAuthor Commented:
Excellent contributor to the site!
0
Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

 
TampaJayAuthor Commented:
I actually spoke a little too soon...

The logic you provided will now give me 'DATABASE CONNECTION FAILED' instead of 'NO USER FOUND'
0
 
TampaJayAuthor Commented:
Error I'm getting is as follows:

ERROR 2005 (HY000): Unknown MySQL server host 'database' (0)

However, this isn't being recognized properly.
0
 
woolmilkporcCommented:
Did you put all if's, then's and else's in the right places?

It might be that the "mysql" executable would issue a nonzero returncode when a "no record found" occurs (yet I don't believe so).
I'll check that.
0
 
TampaJayAuthor Commented:
NVM, user error :-)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.