5
2

More than 3 years have passed since last update.

シェルスクリプト 数値計算 bc コマンド

Last updated at Posted at 2020-06-04

bc コマンド

ー任意の精度(小数点以下の桁数を指定)の数値を扱い、四則演算・平方根・三角関数など様々な数学関数を計算できる

【前提】
bcコマンドはインストールしないと利用できないので以下のコマンドでインストールしておいてください

$bc
$ sudo yum install bc

単純な計算

計算内容を文字列として | を使って、bcコマンドに渡すと計算する。

足し算(例
[hkoen@localhost ~]$ echo "20.5+5" | bc
25.5
割り算(例
[hkoen@localhost ~]$ echo "20.5/5" | bc
4

複雑な計算

-l を利用すると標準数学ライブラリを読み込んでより複雑な数学関数を実行します

平方根(例
[hkoen@localhost ~]$ echo "scale=20;sqrt(20.5/5)" | bc -l
2.02484567313165869332

上記は√(20.5/5)の計算結果を小数点第20位まで表示するという意味です。

シェルスクリプトで書いてみる

base10.sh (任意)というシェルスクリプトファイルに記述します。

base10.shファイル内容
#!/bin/bash

echo "20.5+5" | bc
echo "20.5*5" | bc
echo "scale=10;sqrt(2)" | bc -l
echo "$1 + $2" | bc     #引数1,引数2 を設定
base10.shファイル実行結果
[hkoen@localhost ~]$ chmod 755 base10.sh
[hkoen@localhost ~]$ ./base10.sh 7 9
25.5
102.5
1.4142135623
16

まず、chmod 755 base10.sh でユーザーにファイルの実行権限を付与します。

そして ./bas10.sh を呼んだ後に引数1、引数2:7、9を指定して実行します。

正常に計算してくれています。

5
2
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
5
2