Ubuntu的任何命令行计算器?

我正在寻找一个可以在终端本身进行计算的计算器,没有任何其他额外的前缀和后缀。

例如:如果我在终端输入类似10000-9000的内容,答案应为1000。

我再一次说,我只需要在终端中使用快速计算器,不添加任何字符。 我知道如果我切换到Python,它可以做到这一点,但我不希望它以这种方式。

Bash算术

另一种可能的解决方案是为Bash的内置算法添加一个简单的函数。 把它放在你的.bashrc文件中试试:

 =() { echo "$(($@))" } 

所以现在,你甚至不需要$((...)) ,只是=这看起来很自然。

替换

另一件事是你想要更快:你可以用+替换p和用*替换x 。 这将适用于此:

 =() { local IFS=' ' local calc="${*//p/+}" calc="${calc//x/*}" echo "$(($calc))" } = 5 x 5 # Returns 25 = 50p25 # Returns 75 

现在你甚至不再需要Shift了,唯一的事就是=在算术前面。

hex输出

如果需要,输出可以十进制和hex显示。 ( 注意 :使用x替换会与0x... hex语法冲突)

 =() { local answer="$(($@))" printf '%d (%#x)\n' "$answer" "$answer" } 

例:

 $ = 16 + 0x10 272 (0x110) $ = 16**3 + 16**4 69632 (0x11000) 

使用bc

如果你想要稍微更高级的计算,可以将它管道输出为bc如下所示:

 =() { local IFS=' ' local calc="${*//p/+}" calc="${calc//x/*}" bc -l <<<"scale=10;$calc" } = 'sqrt(2)' # Returns 1.4142135623 = '4*a(1)' # Returns pi (3.1415926532) 

bc提供的function如下(可以从man bc找到):

 sqrt ( expression ) The value of the sqrt function is the square root of the expression. If the expression is negative, a run time error is generated. s (x) The sine of x, x is in radians. c (x) The cosine of x, x is in radians. a (x) The arctangent of x, arctangent returns radians. l (x) The natural logarithm of x. e (x) The exponential function of raising e to the value x. j (n,x) The Bessel function of integer order n of x. 

它还支持ifforwhile和变量,如编程语言,尽管如果你想要它可能更好地写入文件。

请记住,它将在函数/变量名称中替换px 。 最好只删除替换件。

使用gcalccmd

您也可以使函数调用gcalccmd (来自gnome-calculator ),如下所示:

 =() { local IFS=' ' local calc="$*" # Uncomment the below for (p → +) and (x → *) #calc="${calc//p/+}" #calc="${calc//x/*}" printf '%s\n quit' "$calc" | gcalccmd | sed 's:^> ::g' } = 'sqrt(2)' # Returns 1.4142135623 = '4^4' # Returns 256 

可用函数似乎是(直接来自源代码 ), ==表示等效函数:

 ln() sqrt() abs() int() frac() sin() cos() tan() sin⁻¹() == asin() cos⁻¹() == acos() tan⁻¹() == atan() sinh() cosh() tanh() sinh⁻¹() == asinh() cosh⁻¹() == acosh() tanh⁻¹() == atanh() ones() twos() 

您可以使用((...))语法在bash中本机执行简单的整数运算,例如

 $ echo $((10000-9000)) 1000 

还有bc计算器,它可以接受标准输入上的算术表达式

 $ echo "10000-9000" | bc 1000 

bc程序也可以进行浮点运算

 $ echo "scale = 3; 0.1-0.09" | bc .01 

你可以使用calc 。 默认情况下不安装,但您可以使用以下命令快速安装它:

 sudo apt-get install apcalc 

安装完成后,您可以进行任何计算:

 $ calc 5+2 7 $ calc 5-2 3 $ calc 5*2 10 $ calc 5/2 2.5 $ calc 5^2 25 $ calc 'sqrt(2)' 1.4142135623730950488 $ calc 'sin(2)' 0.9092974268256816954 $ calc 'cos(2)' -0.416146836547142387 $ calc 'log(2)' ~0.30102999566398119521 $ calc 'sqrt(sin(cos(log(2))))^2' ~0.81633199125847958126 $ # and so on... 

有关更多信息,请查看其手册页

不幸的是,没有“更容易”的方法来做到这一点。 命令行上的交互式python接口最适合您的需求,因为与apcalc \不同, python 包含在Ubuntu中。 我不确定bc是否仍然包含在内,但是,python是这个东西的最爱。

您可以在命令行上运行交互式python接口,然后以这种方式进行数学运算。 您可以将其用作计算器。

为此,打开终端,输入python ,然后按Enter按钮。

然后,在显示的python提示符中,您可以输入数学。例如, 10000 - 9000 。 下一行输出结果。


但是,如果你的意思是,你只需加载终端并可以做到这一点……

  $ 10000  -  9000
 1000
 $ 

…然后没有办法在没有其他任何东西的情况下在终端中做到这一点,因为Bash不会像这样处理数字参数。

我建议你为基本的Python计算创建一个简单的函数。 你的.bashrc有这样的东西:

 calc() { python3 -c 'import sys; print(eval(" ".join(sys.argv[1:])))' "$@" } calc 5 + 5 # Returns 10 result="$(calc 5+5)" # Stores the result into a variable 

如果要进行更高级的数学运算,可以使用以下导入所有math模块函数的math 。 (有关详细信息,请参阅此处 )

 calc() { python3 -c 'from math import *; import sys; print(eval(" ".join(sys.argv[1:])))' "$@" } calc 'sqrt(2)' # Needs quotes because (...) is special in Bash # Returns 1.4142135623730951 result="$(calc 'sqrt(2)')" # Stores the result into a variable 

(注意:因为Python是一种编程语言,有些东西可能看起来很奇怪,例如**代表的幂和%的代数)

或者,您可以创建Python脚本calc

 #!/usr/bin/python3 from math import * import sys print(eval(' '.join(sys.argv[1:]))) 

将它放在PATH变量中包含的目录中,并设置其可执行标志以获得与上面相同的calc命令(无需创建Bash函数来运行Python脚本)。

如果你想在纯Bash中使用方法,请使用steeldriver的答案。 如果您需要更高级的函数(即来自math ),这个答案才真正有用,因为与Bash相比,Python相对较慢。


我不确定这是否会打破你的“切换到python它可以做到这一点而我不希望它以这种方式。” 请注意,但您不需要输入交互式提示,并且可以在Bash中访问结果,因此这个答案似乎是有效的(至少对我来说)。

使用gnome-calculator (> = 13.04)或gcalctool (<13.04)包中的gcalctool 。 我认为默认安装包

 % gcalccmd > 2+3 5 > 3/2 1.5 > 3*2 6 > 2-3 −1 > 

这是一个快速的shell脚本:

 #!/bin/bash echo "$@" | bc 

将其保存为“c”,然后将其放在路径中的某个位置(例如/ bin),然后将其标记为可执行文件。

 # nano /bin/c # chmod +x /bin/c 

从现在开始,您可以在终端中运行计算,如下所示:

 $ c 10000-9000 1000 

这是对/etc/bash.bashrc (在Ubuntu 10.04上)的相应部分的修改,如果未知命令的第一个字符是数字或-+ ,它将修改command_not_found处理程序以运行shell的表达式求值程序。

你将能够以这种方式进行任何shell算术; 有关算术运算符列表,请参见http://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic 。

请注意,如果要评估的表达式包含* ,则必须使用\或引号引用* ,因为shell将在确定要运行的命令之前执行文件名扩展。 其他运营商也是如此>>

把它放在你的~/.bashrc ,然后输入. ~/.bashrc . ~/.bashrc并尝试一下。

 # if the command-not-found package is installed, use it if [ -x /usr/lib/command-not-found -o -x /usr/share/command-not-found ]; then function command_not_found_handle { if [[ $1 == [0-9+-]* ]]; then echo $(( $@ )) elif [ -x /usr/lib/command-not-found ]; then /usr/bin/python /usr/lib/command-not-found -- $1 return $? elif [ -x /usr/share/command-not-found ]; then /usr/bin/python /usr/share/command-not-found -- $1 return $? else return 127 fi } fi 

示例输出:(我输入的是cta ,一个错字,只是为了测试我们新的command_not_found处理程序仍将尝试查找未知命令)。

 mp@ubuntu:~$ cta No command 'cta' found, did you mean: Command 'cda' from package 'xmcd' (universe) Command 'cat' from package 'coreutils' (main) cta: command not found mp@ubuntu:~$ 9000-1000 8000 

我在这里没有提到的另一个解决方案是Qalculate(qalc)

 sudo apt-get install qalc 

对于CLI版本,

 sudo apt-get install qalculate-gtk 

用于GUI。

它有许多function,例如:

  • 支持单位 :例如20 m / s * 12 h = 864 kilom
  • 内置常量 ,如piecavogadro
  • 许多内置函数 :例如sin(pi) = 0gamma(4) = 6 5! = 120 5! = 120log(1024, 2) = 10
  • 单位转换,例如:

> 120 in
120 * inch = 120 in
> convert cm
120 in = 304.8 centim

  • 符号计算 ,例如(x + y)^2 = x^2 + 2xy + y^2
  • 积分,例如integrate 3*x^2 = x^3diff sin(x), pi
  • 内置帮助,例如help converthelp integrate
  • 选项卡完成命令
  • 一切都被翻译了,例如我的系统是荷兰语,所以我可以写出factorial(5)faculteit(5)
  • 和更多…

你说你想在没有前缀的情况下使用它,那么……你可以使用前缀:

$ qalc 5 ft + 3 cm
(5 * foot) + (3 * centim) = 1.554 m

以及作为repl运行它。

dc ! 它是coreutils的一部分,所以它安装在OS X,Ubuntu以及其他几乎所有的东西上。 这是一个RPN计算器,所以如果你不喜欢它,它不适合你。

非常基本的命令如下(手册页具有我没有包含的所有语法。指数,任何人?)

你只需要数字之间的空格。 在所有其他情况下,它们都被忽略。

键入数字会将其推送到堆栈顶部。

 + Adds top 2 items in stack, then pushes result to stack (`2 4 +p` outputs 6) - Subtracts top 2 items in stack, then pushes result to stack (`4 2 -p` outputs 2) * Multiplies top 2 items in stack, then pushes result to stack (`6 5 *p` outputs 30) / Divides top 2 items in stack, then pushes result to stack (`54 7 /p` outputs 8) p Print top item in stack, without destroying it c Clear stack r Swap top 2 items on stack d Duplicate top item on stack k Pops top item off stack, using it to determine precision (so 10 k would print 10 numbers after the decimal point). Default is 0, so it won't do floating point math by default. n Pops top value off stack, then sends to stdout without a trailing newline f Dump stack. Useful for finding what something does 

我使用Octave来做这类事情: http : //www.gnu.org/software/octave/

它几乎是一个matlab克隆(如果这是一个过度简化的道歉),可以通过输入八度音程在终端中使用。 安装sudo apt-get install octave

它不是你想要的,但我想我会把它添加为python的替代品。

用法示例:

 ~ $ octave octave:1> 9000 - 8000 ans = 1000 octave:2> 

我非常喜欢wcalc。 这是一个命令行科学计算器。 在Ubuntu软件中心很容易找到,或者只是使用apt-get。

 sudo apt-get install wcalc 

它接受命令行参数以及“shell”模式:

 # simple operation $ wcalc 2+2 = 4 # Quoting is necessary to prevent shell from evaluating parenthesis $ wcalc "(2+2)*10" = 40 $ wcalc "sqrt(25)" ~= 5 # in shell mode you can evaluate multiple commands repeatedly $ wcalc Enter an expression to evaluate, q to quit, or ? for help: -> 12*20+1 = 241 -> sin(90) = 1 -> sin(pi/2) = 0.0274121 

如果某人在工程中,像我一样,你可以使用GNU Octave。 它可以做各种事情,绘图,求解联立方程。 此外,它是Matlab的免费替代品

简单的方法是调用python。

例:

 > python -c 'print 10000-9000' 

我发现的是,我不能信任expr,bc或内置的Shell选项。 因此我使用Perl,它通常安装在* linux发行版中

 perl -le 'printf "%.0f", eval"@ARGV"' "($VAL2-$VAL1)" 

上面的计算将从$ VAL2减去$ VAL1并打印没有小数位(0f)

使用Perl的好处是( 此处列出的优缺点详情)

  • 更好的错误捕获(除以0不会停止计算)
  • 可以在配置文件中提供公式。 无需使用复杂的正则表达式逃脱

您可以在.bashrc文件中添加以下function:

 function = { echo "$@" | bc -l } 

请注意, -l标志非常重要。 没有它,使用bc得到bc 5 / 2 = 2

如上面所述,可以使用公式前面的=符号进行计算。

您也可以使用awk在终端上进行一些算术运算,

 echo 10000 9000 | awk '{print $1-$2}' 1000 echo 10000 9000 | awk '{print $1+$2}' 19000 echo 10000 9000 | awk '{print $1/$2}' 1.11111 echo 10000 9000 | awk '{print $1*$2}' 90000000 

使用“bc”命令然后你可以做计算

 [root@vaibhav ~]# bc ----------these lines will genrate automaicaly--------------- right 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc. This is free software with ABSOLUTELY NO WARRANTY. For details type `warranty'. ---------------enter your calculation here--------------------------------------- 10+2 12 

要在没有保修说明的情况下使用bc ,请在终端bc -q写入

 [root@vaibhav ~]# bc -q 10+2 12 

您可以使用bind和bash CaCe来控制输出。 例如,在shell中执行此操作:

 bind '"\Cj": "\C-aecho $(( \Ce )) \Cm"' 

现在输入10 + 15等任何算术运算,然后按Ctrl + J

 $ echo $(( 10 + 15 )) 25 

你会得到这个。 现在,它是如何完成的?

  • bind此命令会更改bash的绑定,如快捷键。
  • \Cj这是等同于Ctrl + J的bash,这是我们想要添加到命令的组合键。
  • \Ca这将我们带到了线的起点。
  • echo $((这写echo $((在开头。
  • \Ce把我们带到了最后
  • ))关闭我们之前的括号
  • \Cm这相当于返回键。

您可以将其写入~/.inputrc文件:

 "\Cj": "\C-aecho $(( \Ce )) \Cm" 

当然,其他答案也是有效的! 刚调整一下:

  • bc: "\Cj": "\C-aecho " \Ce " | bc \Cm"
  • apcalc: "\Cj": "\C-acacl \Cm"
  • python: "\Cj": "\C-apython3 -c "print( \Ce )" \Cm"
  • 还有别人吗?

您可以将Ctrl + J更改为您喜欢的任何内容,但请记住,尽量不要为已经有绑定的内容更改它;)。

资源:

  • 有没有办法将bash配置为始终页面输出?

在过去,我使用了wcalc和一个名为e的小程序,谷歌几乎不可能。 现在我使用python脚本来执行此操作,它使用e一些function,如方括号。 wcalc仍然很好,因为它可以进行任意精度和单位转换,但我几乎从不使用这些function。

 #!/usr/bin/env python3 """ This is a very simple command line calculator. It reads in all arguments as a single string and runs eval() on them. The math module is imported so you have access to all of that. If run with no arguments, it allows you to input a single line expression. In the case of command line args, square brackets are replaced with round parentheses, because many shells interpret round parentheses if they are not quoted. """ import sys, numbers import cmath, math args = sys.argv[1:] if len(args) < 1: expr = input() else: expr = " ".join(args[:]) expr = expr.replace("[", "(").replace("]", ")") def log2(x): """Return the base-2 logarithm of x.""" return cmath.log(x, 2) # the smallest number such that 1+eps != 1 # (this is approximate) epsilon = sys.float_info.epsilon env = math.__dict__ env.update(cmath.__dict__) env = {k:v for k,v in env.items() if not k.startswith("__")} env["eps"] = epsilon env["log2"] = log2 env["inf"] = float("inf") env["nan"] = float("nan") res = eval(expr, env) # throw away small imaginary parts, they're probably just due to imprecision if (isinstance(res, numbers.Number) and res != 0 and abs(res.imag)/abs(res) < 10*epsilon): res = res.real print(str(res).replace("(", "[").replace(")", "]")) 

以下是如何使用它(假设脚本已保存为e并放在$PATH某个位置):

 $ ee**[pi*1i] -1.0 $ e hex[10**3] 0x3e8 $ e "[0o400+3]&0xff" # need quotes because of '&' 3 

有一步完成你想要的方法。 您需要做的就是将帐户的shell设置为/bin/bc

您还可以使用printf shell builtin在终端上进行算术计算。

 printf `expr $num1 + $num2` # num1,num2 are variables which stores numbers as values. 

例:

 $ printf "$(expr 10000 + 9000)\n" 19000 $ printf "$(expr 10000 - 9000)\n" 1000 

您可以使用python解释器进行计算。 这是一个如何操作的教程 。

默认情况下,Python 2和python 3安装在Ubuntu中。

 $ python Python 2.7.12 (default, Nov 19 2016, 06:48:10) [GCC 5.4.0 20160609] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 2+2 4 >>> 3*5 15 

创建终端计算器

将以下内容放在.bashrc文件中

 function calc { echo "${1}"|bc -l; } 

或者,在shell提示符下运行它。 现在来自shell的“calc”将按如下方式工作:

 $ calc 3+45 48 

带“(”或“)”的所有函数必须用引号括起来。