3

I have a query that returns some numbers from the db and I'm trying to put that into a file to send out. However, some of the values come back as null and I'm trying to substitute '0' in for some calculations in those cases. The only time I can get it to '0' it also does that for variables that have actual values. Below is my code and output. What am I doing wrong? (Very new to bash/Linux.)

I use these commands:           and I get this output:
echo ${awb-$defaultbase}            NULL
echo ${gachurn-$defaultbase}        2 - 
echo ${awb+$defaultbase}            0
echo ${gachurn+$defaultbase}        0 - 
echo ${awb:-$defaultbase}           NULL
echo ${gachurn:-$defaultbase}       2 - 
echo ${awb:+$defaultbase}           0
echo ${gachurn:+$defaultbase}       0 - 
echo $awb                           NULL
echo $gachurn                       2

I want the first value to be 0 and the second to be 2.

Lu_Bu
  • 31
  • So I just realized that the value of awb may just be the text "NULL" and not actually null. That seems like the only explanation to me as to why I get what I get. Also, this thread has been helpful: https://unix.stackexchange.com/questions/122845/using-a-b-for-variable-assignment-in-scripts/122848#122848 – Lu_Bu Nov 13 '15 at 21:11
  • Yep. That was it. I had to use if statements but if there is a better way let me know. if [ "$gachurn" == NULL ]; then gachurn=0; fi – Lu_Bu Nov 13 '15 at 21:28

2 Answers2

1

NULL, given back from the database, is a string of four characters and will not be interpreted as the "null string" (empty string) by the shell.

To check whether $awb is NULL and replace it with zero, you may for example do

[ "$awb" = 'NULL' ] && awb=0

This is slightly shorter to write than

if [ "$awb" = 'NULL' ]; then
    awb=0
fi

In bash, you may also do a string substitution, as G-Man suggests:

awb=${awb/NULL/0}
Kusalananda
  • 333,661
0

You can use "${awb/NULL/0}", which does a simple search and replace.  Beware that this will find and replace substrings, so, if the value of the variable is NULL_and_VOID, you will get 0_and_VOID.

Also note that you should always quote all references to shell variables (as shown above) unless you have a good reason not to, and you’re sure you know what you’re doing.