0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

絶対値を取得したい

Posted at

背景・目的

  • ShellScriptで引数から受け取った値をループに使用したかった
  • 負の数が指定されることもあるので絶対値を取得したかった

コマンド

$ num="$1"
$ abs="${num#-}"

ミニ解説

  • ${num#-}は最短一致で指定した文字の右側を取得する
  • --3のようにハイフン2つつけられると最初のハイフンしか削除されないので注意

補足

この方法は数値ではなく文字列として-を削除しているだけ。
厳密に数値として扱いたい場合は他のバリデーションと併用すること。
また、数値として絶対値を取得するなら以下。

$ abs=$((num < 0 ? -num : num))

関連

  • 変数の加工方法(部分削除、抜き出し)(記事作成中)
  • ShellScriptの引数チェック(記事作成中)
0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?