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?

More than 3 years have passed since last update.

ログインシェルがbashの環境でzshの算術演算を使う

Posted at

ログインシェルがbashの環境でコマンドラインからzshの組み込み算術演算を使ったり、bashスクリプトの中で算術演算だけzshのものを使いたい場合のメモ

bashとzshの算術演算の違い

bashもzshも組み込みの算術演算があり電卓代わりに使うには$((...))で囲むだけなのでexprbcコマンドより簡単なので便利である。しかしながら、zshの算術演算は小数点演算、**によるべき乗計算、指数形式の数値の読み込みなど色々できるのに対し、bashの組み込み算術演算は整数演算しかできないのでログインシェルがbash環境のサーバーでは組み込み算術演算を使うには制約が多く不便である。

zsh
$ echo $((1+2))
3

$ echo $((0.5+2))
2.5

$ echo $((1 + 2e+3))
2001.

$ echo $(( 2.0**(1.0/3.0) ))
1.2599210498948732
bash
$ echo $((1+2))
3

$ echo $((0.5+2))
bash: 0.5+2: syntax error: invalid arithmetic operator (error token is ".5+2")

$ echo $((1 + 2e+3))
bash: 1 + 2e: value too great for base (error token is "2e")

$ echo $(( 2.0**(1.0/3.0) ))
bash: 2.0**(1.0/3.0) : syntax error: invalid arithmetic operator (error token is ".0**(1.0/3.0) ")

bashのログインシェルでzshの算術演算を使う

zshがインストールされているものの、ログインシェルにbashが推奨されている環境やbashスクリプトだが算術演算だけzshの組み込みを使いたい場合が対象。

bashからzshのコマンドオプションを指定して実行するだけ。

bash
$ zsh -c 'echo $((0.5+2))'
2.5

シングルクォーテーションでなくダブルクォーテーションを使ってしまうと先に変数が展開されるので注意。

bash
$ zsh -c "echo $((0.5+2))"
bash: 0.5+2: syntax error: invalid arithmetic operator (error token is ".5+2")

bashで指定した変数を使う場合

シングルクォーテーションで指定してbashの変数展開をさせないようにしたが、zshのコマンドオプションの引数として渡すことができる。

bash
$ a=1e+3
$ b=0.25

# 変数展開されないので反映されない
$ zsh -c 'echo $(($a+$b))'
zsh:1: bad math expression: operand expected at end of string

# 引数として変数を渡し、算術演算内の変数名は引数番号を指定する
$ zsh -c 'echo $(($0+$1))' $a $b
1000.25
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?