Bash

Bash 作為浮點計算器

  • January 4, 2017

我用來編寫一個計算浮點數的函式。

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

這很好用,但我想知道是否有一種方法可以完全利用嘗試浮點操作時返回的錯誤消息來省略函式呼叫。

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

這是可行的嗎?如果是這樣,怎麼做?

編輯

我猜反對票意味著我沒有考慮清楚這一點,儘管澄清評論會有所幫助。

我使用mt函式進行計算,但在短時間內執行許多計算時,我經常忘記 mt。一個初始的和獨特的函式呼叫就可以了,為此我可以簡單地使用 python 並稱之為一天。

對不起我的無知。

將此添加到將載入到您的 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.

引用自:https://unix.stackexchange.com/questions/334734