-   Linux - Newbie (
-   -   converting string in integer in bash script (

dziadgba 06-10-2007 09:01 AM

converting string in integer in bash script
hello everybody,
I tried the following bash script


#get number of lines of file nodesAndCoordinates
  lines= wc -l nodesAndCoordinates | gawk  '{print  $1}'

  echo $lines

  echo "done"
  lines=`expr $lines + 1`
  echo $lines

- 23

why does it not give the right value (24)
I suppose that the number 23 is somehow stored in the variable lines as string and not as number. Can that be true? How can I convert variable lines in a number?

any help is appreciated

druuna 06-10-2007 09:25 AM


the lines= wc -l....... part isn't syntactically correct, it should be:

lines="`wc -l nodesAndCoordinates | gawk '{print 23}'`"

Besides that, the above line is strange. The output of the wc -l part is discarded (it is given to gawk, but gawk only prints 23) and 23 is printed. I don't know if the output of the wc -l line is actually needed, if not do something like this: lines="23".

Hope this helps.

dziadgba 06-11-2007 07:35 AM

I am sorry: the correct code is

lines= wc -l nodesAndCoordinates | gawk '{print $1}'

and the output would be 23.
The problem however remains the same.

druuna 06-11-2007 07:50 AM


You are still using the wrong syntax:

It should be: lines=`wc -l nodesAndCoordinates | gawk '{print $1}'`
There should be backticks (`) around the statement.

I always surround a declaration with double quotes. I.e:

lines="`wc -l nodesAndCoordinates | gawk '{print $1}'`"

tlinux17 08-31-2009 06:25 PM

for increase a numeric variable, you can use this sintax
lines=$(($lines + 1))

chrism01 08-31-2009 06:59 PM

Actually, you don't require the '$' inside the parentheses, in fact you can even do

(( a++ )) # Post-increment 'a', C-style.

All times are GMT -5. The time now is 03:05 AM.