test a variable to see if it contains information
Hi guys,
I am trying various ways to test a variable in bash to see if it contains information. I am aware of many different ways to do this, but would like to see if anyone knows of some nice builtins that can do this in various ways. For instance I am fooling around with this to test to see if a mysql query returns information.
VAR=`some mysql query here`
if [ -n $VAR ]
then
echo "query returned no data"
else
echo "$VAR"
fi
The problem with that is that if $VAR contains multiple lines or words then the if statement errors. If you put $VAR in "s then it simply retuns "query returned no data every time". I was just fooling around and wanted to see what you guys have done before in this situation.
Also, i have been wondering how to test if a variable declaration fails. For example:
VAR2=`cat $FILE | grep "$LINE" | awk -F"$WORD" '{print $2}'`
That variable declartion could error for various reasons. $LINE could contain bad characters. $WORD could have bad characters or its initial declaration could have been made something unexpected, etc. I'd like to catch something like that immediatly before i get to a section of code later on which depends on the accuracy of that variable.
OR
What if an if statement errors. How do i tell a script to exit (or continue in a loop) if an if statement generates and error? These are just questions i have had lately. I am not much of a programmer at all nor am I by any means a linux power user, but i enjoy learning new things. Please let me know if anyone has any answers that I can work with.
NOTE: I'm going to bed now, so it will be a few hours before i am able to reply!
|