浮動小数点計算器としてのBash

浮動小数点計算器としてのBash

使ったこれ浮動小数点数を計算する関数を作成します。

mt (){
echo "$1" | bc -l | awk '{printf "%f", $0}'
echo ' ' 
}

これはうまくいきますが、方法があるかどうか疑問に思います。関数呼び出しを完全に省略浮動小数点演算を試みるときに返されるエラーメッセージを活用してください。

$ 45.0+1.2
-bash: 45.0+1.2: command not found

これは可能ですか?それでは、どうすればいいですか?

編集する

私は反対投票が私がこれを十分に考えていないことを意味すると思いますが、明確な意見が役に立ちます。

私が使っていたのは計算をするときに関数を使うのですが、短い時間に多くの計算をしてみるとmtを忘れてしまうことが多いです。この目的には、最初の唯一の関数呼び出しが必要です。私は単にPythonを使用して一日に呼び出すことができます。

私の無知について申し訳ありません。

ベストアンサー1

Bash環境にロードされる場所にこれを追加します:(~/.bashrcはオプションです)(これは悪い考えです。スペースなしで除算は機能しません。理由については、抜粋されたマニュアルページを参照してください。 (一部のGAWKではなくAWKバージョンのみを終了する必要があります)

command_not_found_handle() { 
    # AWK version, security risk
    awk "BEGIN { print $*; exit; }" # Use AWK as a calculator
    # If you want to keep what you did previously:
    # BC version, possibly less of a security risk, but an extra process is involved
    # echo "$*" | bc -l | awk '{printf "%f\n", $0}'
    echo "$0: $1: command not found" 1>&2 # Send error to STDERR
    exit 127 # Keep same exit status as otherwise
}

bashのマニュアルページから:(この関数はbashが他のすべてのオプションを使用したときに呼び出されます)

If  the name is neither a shell function nor a builtin, and contains no
slashes, bash searches each element of the PATH for  a  directory  con-
taining  an  executable  file  by that name.  Bash uses a hash table to
remember the full pathnames of executable files (see hash  under  SHELL
BUILTIN  COMMANDS  below).  A full search of the directories in PATH is
performed only if the command is not found in the hash table.   If  the
search is unsuccessful, the shell searches for a defined shell function
named command_not_found_handle.  If that function exists, it is invoked
with  the  original command and the original command's arguments as its
arguments, and the function's exit status becomes the  exit  status  of
the  shell.  If that function is not defined, the shell prints an error
message and returns an exit status of 127.

おすすめ記事