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

シェルで簡易計算機

Posted at

簡易計算機

環境

  • CentOS release 6.5 (Final)
  • bash 4.1.2

つうか ? を関数名に使えるの ?

関数定義して

? () { echo "$*" | bc -l; }

使う

? "1+2+3+4+5*10"
#=> 60

他にも色々

? が使えるのなら 他にも +-@_[]=!^#<>なども使えるのかなと試したら結構使える...恐るべし

+ () { echo "$*" | bc -l; }
- () { echo "$*" | bc -l; }
@ () { echo "$*" | bc -l; }
[ () { echo "$*" | bc -l; }
] () { echo "$*" | bc -l; }
_ () { echo "$*" | bc -l; }

for x in "@" "-" "+" "_" "[" "]"
do
  echo -n "${x}: "; eval $x "8*5"
done

# こんな結果で
#    @: 40
#    -: 40
#    +: 40
#    _: 40
#    [: 40
#    ]: 40

これとか [ 再定義できるのも恐ろしい。(/usr/bin/[)

$ which [
/usr/bin/[
$ ls -l /usr/bin/[
-rwxr-xr-x 1 root root 33408 Mar 12 20:12 /usr/bin/[

# "[" はコマンドなので普通のbashスクリプトが動かなくなっちゃう
$ [ -f /etc/hosts ] && echo "ok"
(standard_in) 1: syntax error
ok

無理なものは無理だよね

無理強いは良くないです。

$ ! () { echo "$*" | bc -l; }
-bash: syntax error near unexpected token `)'

$ ^ () { echo "$*" | bc -l; }
-bash: :s^ () { echo "$*" | bc -l; }: substitution failed

$ | () { echo "$*" | bc -l; }
-bash: syntax error near unexpected token `|'

$ % () { echo "$*" | bc -l; }
$ % "1+2+3"
-bash: fg: %: no such job

使い処によっては分かりやすいかも

$ is_linux? () { [ `uname` = "Linux" ] && true || false; }
$ is_linux? && echo ok
ok

参考

Commandlinefu
http://www.commandlinefu.com/commands/view/2520/define-a-quick-calculator-function

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