Check whether input is numeric

Hello there, find below for my code first:

$pdp_asaba=`cat /tmp/temp_total | grep asaba | sed 's/[^0-9]*//g'`
if [[ ! $pdp =~ [0-9] ]]
then pdp_asaba=0
fi
$pdp_abuja=`cat /tmp/temp_total | grep abuja | sed 's/[^0-9]*//g'`
if [[ ! $pdp =~ [0-9] ]]
then pdp_abuja=0
fi
$pdp_ojota=`cat /tmp/temp_total | grep ojota | sed 's/[^0-9]*//g'`
if [[ ! $pdp =~ [0-9] ]]
then pdp_ojota=0
fi

What i want is that if the output of cat is not a numeric number, it should give it a value of ZERO but if it is a number then it should continue...

But with the above code i keep getting some "Command Not Found" error:

+ [[ ! 880035 =~ [0-9] ]]
++ cat /tmp/temp_total
++ grep abuja
++ sed 's/[^0-9]*//g'
+ =925605
pdp_total.sh: line 23: =925605: command not found

I know the conditional statement is incomplete, will appreciate your inputs.

$variablename is replaced with the variables value when your script is executed. If you wish to assign a value to a variable do not put a $ sign in front:

pdp_asaba=`cat /tmp/temp_total | grep asaba | sed 's/[^0-9]*//g'`
if [[ ! $pdp =~ [0-9] ]]
then pdp_asaba=0
fi
pdp_abuja=`cat /tmp/temp_total | grep abuja | sed 's/[^0-9]*//g'`
if [[ ! $pdp =~ [0-9] ]]
then pdp_abuja=0
fi
pdp_ojota=`cat /tmp/temp_total | grep ojota | sed 's/[^0-9]*//g'`
if [[ ! $pdp =~ [0-9] ]]
then pdp_ojota=0
fi
1 Like

Many thanks Cero!!!

Script now working the way it should!!

God bless

You are assingning pdp_asaba, pdp_abuja, and pdp_ojota, but you are testing always the same $pdp variable, that may be set outside the snippet posted. Is that what you want to do?
And, your entire cat | grep | sed pipe organ could be replaced by e.g.

sed -n '/asaba/ s/[^0-9]*//gp' /tmp/temp_total