11# Bash 的基本语法
22
3+ ## 分号
4+
5+ 分号` ; ` 是命令的结束符,使得一行可以放置多个命令,上一个命令执行结束后,再执行第二个命令。
6+
7+ ``` bash
8+ $ clear; ls
9+ ```
10+
311## 命令的分组和合并
412
513Shell 允许将多个命令分组和合并执行。
@@ -32,7 +40,19 @@ $ mkdir foo || mkdir bar
3240
3341## if 结构
3442
35- ` if ` 结构用于条件判断。
43+ ` if ` 结构用于条件判断,符合条件时,才会执行指定的命令。它的语法如下。
44+
45+ ``` bash
46+ if commands; then
47+ commands
48+ [elif commands; then
49+ commands...]
50+ [else
51+ commands]
52+ fi
53+ ```
54+
55+ 这个命令分成三个部分:` if ` 、` elif ` 和` else ` 。其中,后两个部分是可选的。` if ` 后面是判断的条件,如果不成立,并且存在` elif ` 部分,就会进行` elif ` 判断;如果还不成立,并且存在` else ` 部分,则会执行` else ` 代码块。
3656
3757``` bash
3858if test $USER = " foo" ; then
4262fi
4363```
4464
45- ` if test -e filename ` 判断文件是否存在。
65+ 上面的例子中,` if test ` 判断环境变量` $USER ` 是否等于` foo ` ,如果等于就输出` Hello foo. ` ,否则输出其他内容。
66+
67+ ` if ` 结构可以写在一行内。
68+
69+ ``` bash
70+ $ if true ; then echo " It's true." ; fi
71+ It' s true.
72+
73+ $ if false; then echo "It' s true." ; fi
74+ ` ` `
75+
76+ 上面的例子中,` true` 和` false` 是两个特殊命令,前者代表操作成功,后者代表操作失败。
77+
78+ ` if` 结构写成下面两种形式,也是可以的。
79+
80+ ` ` ` bash
81+ # 形式一
82+ if [ -f .bash_profile ]
83+ then
84+ echo " .bash_profile 文件存在"
85+ else
86+ echo " .bash_profile 文件不存在"
87+ fi
88+
89+ # 形式二
90+ if [ -f .bash_profile ]
91+ then echo " .bash_profile 文件存在"
92+ else echo " .bash_profile 文件不存在"
93+ fi
94+ ` ` `
95+
96+ # # test 命令
97+
98+ ` if` 结构往往与` test` 命令一起使用,有两种形式。
99+
100+ ` ` ` bash
101+ # 第一种形式
102+ test 表达式
103+
104+ # 第二种形式
105+ [ 表达式 ]
106+ ` ` `
107+
108+ 注意,第二种形式之中,` [` 和` ]` 与内部的表达式之间都必须有空格。
109+
110+ ` if test -e filename` 判断一个文件是否存在。
46111
47112` ` ` bash
48113if test -e /tmp/foo.txt ; then
@@ -58,6 +123,22 @@ if [ -e /tmp/foo.txt ] ; then
58123fi
59124` ` `
60125
126+ ` test` 命令的参数如下。
127+
128+ - ` -d file` :如果` file` 为目录,返回` true` 。
129+ - ` -e file` :如果` file` 文件存在,返回` true` 。
130+ - ` -f file` :如果` file` 文件存在,并且为一个常规文件,返回` true` 。
131+ - ` -L file` :如果` file` 是一个符号链接,返回` true` 。
132+ - ` -r file` :如果` file` 是一个文件,且用户有读权限,返回` true` 。
133+ - ` -w file` :如果` file` 是一个文件,且用户有写权限,返回` true` 。
134+ - ` -x file` :如果` file` 是一个文件,且用户有执行权限,返回` true` 。
135+ - ` file1 -nt file2` :如果` file1` 比` file2` 更新(根据修改时间),返回` true` 。
136+ - ` file1 -ot file2` :如果` file1` 比` file2` 更旧(根据修改时间),返回` true` 。
137+ - ` -z string` :如果` string` 是一个空字符串,返回` true` 。
138+ - ` -n string` :如果` string` 是一个非空字符串,返回` true` 。
139+ - ` string1 = string2` :如果` string1` 与` string2` 相等,返回` true` 。
140+ - ` string1 != string2` :如果` string1` 与` string2` 不相等,返回` true` 。
141+
61142# # for 循环
62143
63144foo 循环用于命令的重复执行。
0 commit comments