If “NULL” then use 0 in shell scripting

2019-07-27 05:45发布

问题:

I am using a shell script to query a hive table

last_val="`hive -e "select max(id) from ${hivedatabase}.${table}"`"

echo var1="$last_val"

When the last_val = "NULL" then I want the last_val to be zero

I have tried like below but still I am getting Null

function value
{
   if [ "$last_val" = "NULL" ];then
        echo "0"
   elif [ "$last_val" != "NULL" ];then
        echo "$last_val"
   fi
}


echo var2="$(value)"

I want to use this value in for incremental imports using sqoop like

select * from testing.1234abc check column id > value

How can I achieve that in shell scripting

回答1:

I'm using this approach, try it:

#!/bin/bash

hivedatabase=mydb
table=mytable
default_value="ZERO"

last_val=$(hive -e "set hive.cli.print.header=false; select max(id) from ${hivedatabase}.${table};")

if [[ "$last_val" == "NULL" ]] ; then 
  last_val="$default_value"
fi

echo "$last_val"