7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

bashの数字

Posted at

bash等で文字列から切り出した数字を演算して他の数字を作るときの注意

数字として扱うときに頭に0が付いているときは8進数を意味する!

このことすっかり忘れてて大量にJob流した後エラーを捨ててて後になって気がついた
どっかに書いておかないと忘れちゃう(´・ω・`)..ので書いておくw

ダメなケース

A="08"
B="01"
printf "%02d" $(($A + $B))
bash: 08: value too great for base (error token is "08")

そりゃ8進数で8ってあかんよね
というわけ10進数で扱いたいのでこう直す。

printf "%02d" $((10#$A + 10#$B))
09

別の変数に代入するときは、

C=$(builtin printf "%02d" $((10#$A + 10#$B)))
echo$C”
”09”

ジブンのBlogに書いていたのだけど時々忘れて探すのが大変なのでこちらに。

7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?