Why do you always get true? Let's play a little bit in your terminal first:
$ [[ hello ]] && echo "True"
What do you think the output is? (try it!) And with the following?
$ [[ "" ]] && echo "True"
(try it!).
All right, so it seems that a non-empty string is equivalent to the true expression, and an empty string (or an unset variable) is equivalent to the false expression.
What you did is the following:
[[ $var=="" ]]
and
[[ $var!="" ]]
so you gave a non-empty string, which is true!
In order to perform the test, you actually need spaces between the tokens:
[[ $var == "" ]]
instead. Now, your test would be better written as:
if [[ -z "$var" ]]; then
echo "Empty String <<"
else
echo "$CPIC_MAX_CONV"
fi
(without the sub-shells, and with just one test).
There's more to say about your scripting style. With no offence, I would say it's really bad:
Don't use backticks! Use the $(...) construct instead. Hence:
var="$(export | grep -i "CPIC_MAX_CONV" | awk '/CPIC_MAX_CONV/ { print $NF } ')"
Don't use function blah to define a function. Your function should have been defined as:
cpic () {
local var="$(export | grep -i "CPIC_MAX_CONV" | awk '/CPIC_MAX_CONV/ { print $NF } ')"
if [[ -z "$var" ]]; then
echo "Empty String <<"
else
echo "$CPIC_MAX_CONV"
fi
}
Oh, I used the local keyword, because I guess you're not going to use the variable var outside of the function cpic.
Now, what's the purpose of the function cpic and in particular of the stuff where you're defining the variable var? It would be hard to describe (as there are so many cases you haven't thought of). (Btw, your grep seems really useless here). Here are a few cases you overlooked:
- An exported variable is named
somethingfunnyCPIC_MAX_CONVsomethingevenfunnier
An exported variable contains the string CPIC_MAX_CONV somewhere, e.g.,
export a_cool_variable="I want to screw up Randhawa's script and just for that, let's write CPIC_MAX_CONV somewhere here"
Ok, I don't want to describe what your line is doing exactly, but I kind of guess that your purpose is to know whether the variable CPIC_MAX_CONV is set and marked for export, right? In that case, you'd be better with just this:
cpic () {
if declare -x | grep -q '^declare -x CPIC_MAX_CONV='; then
echo "Empty String <<"
else
echo "$CPIC_MAX_CONV"
fi
}
It will be more efficient, and much more robust.
Oh, I'm now just reading the end of your post. If you want to just tell if variable CPIC_MAX_CONV is set (to some non-empty value — it seems you don't care if it's marked for export or not, correct me if I'm wrong), it's even simpler (and it will be much much more efficient):
cpic () {
if [[ "$CPIC_MAX_CONV" ]]; then
echo "Empty String <<"
else
echo "$CPIC_MAX_CONV"
fi
}
will do as well!