Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

atoi() like function in bash?

Tags:

bash

Imagine that I use a state file to store a number, I read the number like this:

COUNT=$(< /tmp/state_file)

But since the file could be disrupted, $COUNT may not contain a "number", but any characters.

Other than using regex, i.e if [[ $COUNT ~ ^[0-9]+$ ]]; then blabla; fi, is there a "atoi" function that convert it to a number(0 if invalid)?

EDIT

Finally I decided to use something like this:

let a=$(($a+0))

Or

declare -i a; a="abcd123"; echo $a # got 0

Thanks to J20 for the hint.

like image 659
daisy Avatar asked May 21 '26 07:05

daisy


1 Answers

You don't need an atoi equivalent, Bash variables are untyped. Trying to use variables set to random characters in arithmetic will just silently ignore them. eg

foo1=1
foo2=bar
let foo3=foo1+foo2
echo $foo3

Gives the result 1.

See this reference

like image 141
jam Avatar answered May 23 '26 22:05

jam