Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string into integer in bash script - "Leading Zero" number error

Tags:

bash

In a text file, test.txt, I have the next information:

sl-gs5 desconnected Wed Oct 10 08:00:01 EDT 2012 1001 

I want to extract the hour of the event by the next command line:

hour=$(grep -n sl-gs5 test.txt | tail -1 | cut -d' ' -f6 | awk -F ":" '{print $1}') 

and I got "08". When I try to add 1,

 14 echo $((hour+1)) 

I receive the next error message:

./test2.sh: line 14: 08: value too great for base (error token is "08") 

If variables in Bash are untyped, why?

like image 665
RobertoFRey Avatar asked Oct 10 '12 14:10

RobertoFRey


People also ask

How do I remove leading zeros in bash?

As $machinenumber that is used has to have a leading zero in it for other purposes, the idea is simply to create a new variable ( $nozero ) based on $machinenumber , where leading zeros are stripped away. $machinetype is 74 for now and hasn't caused any problems before.

What is ${ 0 in bash?

1 Answer. ${0} is the first argument of the script, i.e. the script name or path. If you launch your script as path/to/script.sh , then ${0} will be exactly that string: path/to/script.sh .

What is $# in bash?

$# is a special variable in bash , that expands to the number of arguments (positional parameters) i.e. $1, $2 ... passed to the script in question or the shell in case of argument directly passed to the shell e.g. in bash -c '...' .... .

What does $() mean in bash?

Again, $() is a command substitution which means that it “reassigns the output of a command or even multiple commands; it literally plugs the command output into another context” (Source).


2 Answers

See ARITHMETIC EVALUATION in man bash:

Constants with a leading 0 are interpreted as octal numbers.

You can remove the leading zero by parameter expansion:

hour=${hour#0} 

or force base-10 interpretation:

$((10#$hour + 1)) 
like image 160
choroba Avatar answered Sep 27 '22 18:09

choroba


what I'd call a hack, but given that you're only processing hour values, you can do

 hour=08  echo $(( ${hour#0} +1 ))  9  hour=10   echo $(( ${hour#0} +1))  11 

with little risk.

IHTH.

like image 39
shellter Avatar answered Sep 27 '22 19:09

shellter