# 3. 条件判断

* 格式 \[ 表达式 ]
* 表达式前后各有一个空格

## 文件(夹),路径相关

* -e:(exist)目标是否存在
* -d:(directory)是否为文件夹
* -f:(file)是否为文件

### 例子

1. 判断当前目录下的 1.txt 是否存在,是则输出true

   ```bash
   [ -e 1.txt ]&& echo "true"
   ```
2. 判断dir1是否是目录,是则输出true

   ```bash
   [ -d dir1 ]&& echo "true"
   ```
3. 判断1.txt是否为文件,是则输出true

   ```bash
   [ -f 1.txt ]&& echo "true"
   ```
4. 如果1.txt不存在则创建一个1.txt

   ```bash
   [ -e 1.txt ] || touch 1.txt
   ```

## 权限相关

* -r:(read)是否具有读取权限
* -w:(write)是否具有写入权限
* -x:(excute)是否具有运行权限

### 例子

1. 判断1.txt 是否具有写权限,有则输出success

   ```bash
   [ -w 1.txt ]&& echo "success"
   ```
2. 判断1.txt 是否具有读权限

   ```bash
   [ -r 1.txt ]
   ```
3. 判断1.txt 是否具有执行权限

   ```bash
   [ -x 1.txt ]
   ```

## 整数比较

* -eq:(equal) 等于
* -ne:(not equal) 不等于
* -gt:(greater than) 大于
* -lt:(lesser than) 小于
* -ge:(greater or equal) 大于等于
* -le:(lesser or equal) 小于等于

### 例子

```bash
# 1>2
[ 1 -gt 2 ]

# 1<3
[ 1 -lt 3 ]

# 1<=4
[ 1 -le 4 ]

# 4>=3
[ 4 -ge 3 ]

# 1=2
[ 1 -eq 2 ]

# 2!=3
[ 2 -ne 3 ]
```

## 字符串比较

* \=  :相等
* != :不相等
* -z :判断字符串长度是否为0
* -n :判断字符串长度是否不为0
* $  :判断字符串是否不为空

### 例子

```
# "hello" 与 "hello"比较
[ "hello" = "hello" ]
[ "hello" != "hello" ]
```

demo2

```bash
# 代码
a="abc"
b="efg"
if [ $a = $b ]
then
    echo "equal"
fi

if [ $a != $b ]
then
    echo "not equal"
fi

if [ -z $a ]
then
    echo "zero"
fi

if [ -n $a ]
then
    echo "not zero"
fi

if [ $a ]
then 
    echo "not empty"
fi

# 输出

not equal
not zero
not empty
```

## 小数(浮点型)比较

利用bc计算器比较

* 满足返回 1
* 不满足返回 0

### 例子

5 是否 大于 1.3

```bash
[ `echo "5>1.3"| bc` -eq 1 ]
```

## 逻辑比较

* || :或
* && :且
* !  :非
* -o :或
* -a :且

  **例子**

  \`\`\`bash

  a=123

  b=456

  c=123

  if \[\[ $a -eq $c || $a -lt $b ]]

  then

  &#x20; echo "a = c 或 a < b"

  fi

if \[\[ $a -eq $c && $b -gt $a ]] then echo "a = c 且 b > a" fi

if \[\[ ! $a -ne $c ]] then echo "a = c" fi

if \[ $a -eq $c -o $a -lt $b ] then echo "a = c 或 a < b" fi

if \[ $a -eq $c -a $b -gt $a ] then echo "a = c 且 b > a" fi \`\`\`


---

# 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/3.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.
