使用 Ubuntu 桌面,我打开了终端并使用了 bash shell。bash 的 shell 扩展之一是算术扩展,语法如下:
$(( EXPRESSION ))
or
$[ EXPRESSION ]
Run Code Online (Sandbox Code Playgroud)
当我做算术时,它确实返回了正确的值,但后面总是跟着“找不到命令”:
$ $((1+2))
3: command not found
$ $[1+2]
3: command not found
$ $[2+2]
4: command not found
$ $((2*6))
12: command not found
Run Code Online (Sandbox Code Playgroud)
我的问题是为什么它显示“找不到命令”,我该如何解决?
您必须echo在所有命令之前添加命令,
$ echo $[1+2]
3
Run Code Online (Sandbox Code Playgroud)
您不必直接$[1+2]放在终端上,因为 bash 计算$[1+2]并再次解析相同的内容,因此会出现未找到命令的错误。
$ var="sudo apt-get update"
$ $var
Ign http://archive.canonical.com saucy InRelease
Ign http://ppa.launchpad.net saucy InRelease
Ign http://ubuntu.inode.at saucy InRelease
Ign http://extras.ubuntu.com saucy InRelease
29% [Waiting for headers] [Waiting for headers] [Waiting for headers]
Run Code Online (Sandbox Code Playgroud)
在上面的例子中,sudo apt-get updatecommand 被分配给一个变量var.On running $var,首先 bash 扩展它并再次解析扩展的。
$ $((1+2))
3: command not found
Run Code Online (Sandbox Code Playgroud)
这里发生的事情是bash计算$((1+2))结果为3。 bash然后查找名为3要执行的命令。它找不到它。因此出现了错误。正如@Avinash 建议的那样,使用echo以避免这种情况。
$ echo $((1+2))
3
Run Code Online (Sandbox Code Playgroud)