# 2. shell中的四则运算符

* n1,n2 :常量数字
* char:运算符号 加,减,乘,除,取余(+,-,\*,/,%)
* $a,$b:变量a,变量b

## 方法1

* 数字与符号之间需要有空格
* 不支持小数

> expr n1 char n2
>
> expr $a char $b

* 此种格式中乘号 *需要写成 \\*

  ```bash
  # 例如:100*100
  expr 100 \* 100
  ```

## 方法2

* 数字与符号之间可以不加空格
* 不支持小数&#x20;

> echo $\[n1 char n2]
>
> expr $\[$a char $b]

## 方法3

* 数字与符号之间可以不加空格
* 不支持小数

> echo $((n1 char n2))
>
> echo $(($a char $b))

## 例子

计算:1\*100

```bash
expr 1 \* 100
```

等价于

```bash
echo $[1 * 100]
```

等价于

```
echo $((1 * 100))
```

## linux自带计算器

控制台中使用bc命令进入

成功进入后会显示

```
bc 1.06.95
Copyright 1991-1994, 1997, 1998, 2000, 2004, 2006 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'.
```

输出quit然后回车退出bc计算器

## 方法4

使用bc计算器进行四则运算

* 支持小数

  > echo "n1 char n2" | bc

计算1.2+3.4

```bash
echo "1.2+3.4" | bc
```

### 保留指定小数位数

```bash
  echo "scale=num;n1 / n2" | bc
```

* 加减法无效
* num:代表小数位数
* 结果在(-1,1) 区间里面不显示0

#### 例子

```bash
# 1.2/3 保留２位  = .40
echo "scale=2;1.2/3" | bc

# 1.2 -5   = .40 = -3.8
echo "1.2-5" | bc

# 3 * 5  = 15
echo "3*5" | bc

# 1+2.345 保留两位　
# 3.345
echo "scale=2;1+2.345" | bc 
# 3.34
echo "scale=2;(1+2.345)/1" | bc
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://sugar-at.gitbook.io/blog-article/shell/2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
