Skip to content

Commit 97c1db5

Browse files
committed
docs: edit condition
1 parent 17b5afb commit 97c1db5

3 files changed

Lines changed: 49 additions & 3 deletions

File tree

docs/condition.md

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,19 @@ test expression
105105
[[ expression ]]
106106
```
107107

108-
上面的`expression`是一个表达式,其执行结果是`true`或者是`false`。当表达式为真时,这个`test`命令的返回值为`0`,当表达式为假时,`test`命令的返回值为`1`
108+
上面的`expression`是一个表达式,这个表达式的判断结果是`true`或者是`false`。当表达式为`true`时,`test`命令执行成功(命令的返回值为`0`),当表达式为`false`时,`test`命令执行失败(命令的返回值为`1`)。
109+
110+
```bash
111+
$ test -f /etc/hosts
112+
$ echo $?
113+
0
114+
115+
$ [ -f /etc/hosts ]
116+
$ echo $?
117+
0
118+
```
119+
120+
上面命令使用`test`的两种形式,判断`/etc/hosts`文件是否存在,该命令的返回值为`0`,表示该文件确实存在。
109121

110122
注意,第二种和第三种写法,`[``]`与内部的表达式之间都必须有空格。写法三比前两种写法多出一个功能,就是支持正则判断,其他完全一样,详见后文。
111123

@@ -431,7 +443,7 @@ then
431443
fi
432444
```
433445
434-
上面的例子只有在指定文件里面,同时存在搜索词`word1``word2`,就会执行`if`的命令部分。
446+
上面的例子只有在指定文件里面,同时存在搜索词`word1``word2張上淳`,就会执行`if`的命令部分。
435447
436448
```bash
437449
[[ -d "$dir_name" ]] && cd "$dir_name" && rm *
@@ -488,6 +500,25 @@ esac
488500
489501
上面例子中,最后一条匹配语句的模式是`*`,这个通配符可以匹配没有字符,放在最后表示匹配所有其他情况,类似`if``else`部分。
490502
503+
下面是另一个例子。
504+
505+
```bash
506+
#!/bin/bash
507+
508+
OS=`uname -s`
509+
510+
case "$OS" in
511+
FreeBSD) echo "This is FreeBSD" ;;
512+
Darwin) echo "This is Mac OSX" ;;
513+
AIX) echo "This is AIX" ;;
514+
Minix) echo "This is Minix" ;;
515+
Linux) echo "This is Linux" ;;
516+
*) echo "Failed to identify this OS" ;;
517+
esac
518+
```
519+
520+
上面的例子判断当前是操作系统属于哪一类。
521+
491522
`case`的匹配模式可以使用各种通配符,下面是一些例子。
492523
493524
- `a)`:值等于“a”,则匹配

docs/loop.md

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,21 @@ Bash 提供了两个内部命令,用来在循环内部跳出循环。
6969

7070
`continue`命令立即终止本轮循环,开始执行下一轮循环。
7171

72+
```bash
73+
#!/bin/bash
74+
while read -p "What file do you want to test?" filename
75+
do
76+
if [ ! -e "$filename" ]; then
77+
echo "The file does not exist."
78+
continue
79+
fi
80+
81+
echo "You entered a valid file.."
82+
done
83+
```
84+
85+
上面例子中,只要用户输入的文件不存在,`continue`命令就会生效,直接进入下一轮循环(让用户重新输入文件名),不再执行后面的打印语句。
86+
7287
## until 循环
7388

7489
`until`循环与`while`循环恰好相反,只要不符合判断条件(判断条件失败),就不断循环执行指定的语句。一旦符合判断条件,就退出循环。

docs/variable.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -310,7 +310,7 @@ filename=${1:?"filename missing."}
310310
declare OPTION VARIABLE=value
311311
```
312312

313-
主要参数(OPTION)如下。
313+
`declare`命令的主要参数(OPTION)如下。
314314

315315
- `-a`:声明数组变量。
316316
- `-i`:声明整数变量。

0 commit comments

Comments
 (0)