1828622 Members
1463 Online
109983 Solutions
New Discussion

String to numeric

 
Gyankr
Frequent Advisor

String to numeric

Hi everybody,

I have a simple script as below

dt=20081125
dttb="20081126"
if [ `expr "$dt" - "$dtb"` -eq 1 ]; then
echo "converting"
else
echo "not converting"
fi

How do i convert the variable "dttb" to a numeric,i tried something like this sed 's/"//g' but still no success.

I want the bash script if statement to evaluate to true.How do i do this? I searched the forum but did not get any positive result.

Regards,
Gyan
5 REPLIES 5
James R. Ferguson
Acclaimed Contributor

Re: String to numeric

Hi:

First, you mis-spelled one of your variables --- once it is 'dttb' and once it is 'dtb'.

Second, it appears that you are subtracting the larger value from the smaller and then expecting the result to be a postive value.

Try something like:

#!/usr/bin/sh
dt=20081125
dttb="20081126"
if [ `expr "$dttb" - "$dt"` -eq 1 ]; then
echo "converting"
else
echo "not converting"
fi

...which when run, outputs"

converting

Regards!

...JRF...
James R. Ferguson
Acclaimed Contributor

Re: String to numeric

Hi (again):

It is helpful in scripts to add 'set -u' which causes the shell to treat unset parameters as an error when substituting them. Had you done this with this script:

# cat ./myexpr
#!/usr/bin/sh
set -u
dt=20081125
dttb="20081126"
if [ `expr "$dtb" - "$dt"` -eq 1 ]; then
echo "converting"
else
echo "not converting"
fi

...when you ran it, your output would be:

#./myexpr
./myexpr[5]: dtb: Parameter not set.
./myexpr[5]: test: Specify a parameter with this command.
not converting

This tells you that something is amiss since a "Parameter [is] not set". As noted, originally, the correct line is:

if [ `expr "$dttb" - "$dt"` -eq 1 ]; then

Regards!

...JRF...
Dennis Handly
Acclaimed Contributor

Re: String to numeric

>How do i convert the variable "dttb" to a numeric

If using a real shell, you should use the Arithmetic Evaluation operator:
if [ $((dt - dttb)) -eq 1 ]; then

You can also use it for the whole expression:
if (( dt - dttb == 1 )); then

(Unfortunately I can't remember if the result of this expression is 1 for C, so that the "if" will then be false?)

>JRF: it appears that you are subtracting the larger value from the smaller and then expecting

I assume Gyankr cares about is the answer 1. Perhaps with that negative result, Gyankr wants to test the false case? :-)
Gyankr
Frequent Advisor

Re: String to numeric

Thanks especially to JRF,it was a simple variable mistake.

Regards,
Gyan
Dennis Handly
Acclaimed Contributor

Re: String to numeric

>ME: if (( dt - dttb == 1 )); then
>(Unfortunately I can't remember if the result of this expression is 1 for C,

It works fine. The exit status of let is 0 if the result is non-zero.