Reputation: 122
Can someone explain how the number 2909
is generated in this bash code? and how to fix it without sed/awk/dc.
s="05535"
echo $(( s ))
>> 2909
currently have this is my code which I don't like.
s=$(echo "$s 0 -p" | dc)
Upvotes: 0
Views: 230
Reputation: 84642
In addition to the other methods, simple string indexes can provide both the test and the conversion:
[ ${s:0:1} -eq 0 ] && s=${s:1}
If you are concerned about multiple leading 0
's, then
while [ ${s:0:1} -eq 0 ]; do s=${s:1}; done
Upvotes: 0
Reputation: 786091
2909
is decimal value (base 10) for octal 05535
.
Any number starting from 0
is considered an octal value and ((..))
prints decimal value by default.
To keep number it's decimal value use (thanks to @thatotherguy):
s="05535"
echo $(( 10#$s ))
5535
Upvotes: 2