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.

相关内容