linux-command/command/let.md

123 lines
2.4 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

let
===
简单的计算器,执行算术表达式。
## 概要
```shell
let arg [arg ...]
```
## 主要用途
- 执行一个或多个算术表达式。
## 参数
arg算术表达式
## 返回值
当`let`最后一个执行的表达式的计算结果为0时返回`1`,否则返回`0`。
当`let`执行的表达式的除数为0时返回`1`并报错。
## 运算符优先级递减表
|**运算符**|**描述**|
|:-------:|:-------:|
|```id++, id--```|```变量后增量、变量后减量```|
|```++id, --id```|```变量预增量、变量预减量```|
|```-, +```|```正号、负号```|
|```!, ~```|```逻辑否、按位取反```|
|```**```|```幂运算```|
|```*, /, %```|```乘法、除法、取余```|
|```+, -```|```加法、减法```|
|```<<, >>```|```按位左移、右移```|
|```<=, >=, <, >```|```比较```|
|```==, !=```|```等于、不等于```|
|```&```|```按位与```|
|```^```|```按位异或```|
|```\|```|```按位或```|
|```&&```|```逻辑与```|
|```\|\|```|```逻辑或```|
|```expr ? expr : expr```|```条件运算符(三元运算符)```|
|```=, *=, /=, %=, +=, -=,```<br>```<<=, >>=, &=, ^=, \|=```|```赋值```|
## 例子
```shell
# 尝试直接在终端中执行算术表达式就像在python的IDLE
3+4
bash3+4command not found...
# 换一种方式。
3 + 4
bash3command not found...
# 看来不行。
```
```shell
# let命令赋值。
let a=3**4
echo ${a}
# 显示81。
# ((...))和let命令等效。
((a=3**4))
```
```shell
# let常用于变量赋值而外部命令expr可直接返回表达式的值。
let 3+4
# 没有显示7。
# 执行后显示7注意空格。
expr 3 + 4
```
```shell
# 条件表达式。
if ((8>4)); then
echo '8 is greater than 4.'
else
echo 'error'
fi
# 注意空格。
if [[ 12 -le 10 ]]; then
echo 'error'
else
echo '12 is greater than 10.'
fi
```
```shell
# 可以通过declare命令设置整型属性的方法来进行算术运算。
# local命令与此类似。
# 没有指定整型属性,输出为字符串'a+b'。
declare a=3 b=4 c
c=a+b
echo ${c}
# 不过可以使用以下方式赋值。
c=$((a+b))
echo ${c}
# 显示7
# 设置了整型属性就可以直接加了。
declare -i a=3 b=4 c
c=a+b
echo ${c}
# 同上。
declare -i a
a=2*3
echo ${a}
# 显示6。
```
### 注意
1. 该命令是bash内建命令相关的帮助信息请查看`help`命令。
2. 执行算术计算的命令除了`let`,还有外部命令`expr`、`bc`等。