test -e /tmp; echo $? # 调用 test 判断 /tmp 是否存在, 并打印 test 的返回值 [ -e /tmp ]; echo $? # 和上面完全等价, /tmp 肯定是存在的, 所以输出 0
# if test -e /tmp; then # echo "/tmp exist"; # else # echo "/tmp not exist"; # fi # if [[ -e "/tmp" ]]; then # echo "/tmp exist"; # else # echo "/tmp not exist"; # fi
if [ $string -ne 'abc' ]; then echo"Not equal" else echo"Equal" fi if [ $a -ge $b ]; then echo"Greater equal" else echo"Not greater equal" fi
逻辑运算符
在 [ ] 中使用
在 [[ ]] 和 (( )) 中使用
说明
举例
赋值
a=10
b=25
-a
&&
与运算,两个表达式都为 true,才返回 true
[ $a -lt 20 -a $b -gt 20 ] 返回 true
-o
||
或运算,有一个表达式都为 true,则返回 true
[ $a -lt 20 -o $b -gt 100 ] 返回 true
!
!
非运算,表达式为 true,则返回 false
[ !false ] 返回 true
1 2 3 4 5 6 7 8 9 10 11 12
a=5 b=12 if [ $a -lt 50 -a $b -gt 8 ]; then echo"And(-a) expr result is true" else echo"And(-a) expr result is false" fi if [ $a -lt 50 -o $b -gt 12 ]; then echo"Or(-o) expr result is true" else echo"Or(-o) expr result is false" fi
字符串运算符, [ ] 字符串运算不需要转义
字符串运算符
说明
举例
=
检测两个字符串是否相等,相等则返回 true
[ ${a} = ${b} ]
!=
检测两个字符串是否相等,不相等则返回 true
[ ${a} != ${b} ]
-z
检测字符串长度是否为 0,为 0 则返回 true
[ -z ${b} ]
-n
检测字符串长度是否不为 0,不为 0 则返回 true
[ -n ${b} ]
str
检测字符串是否为 null,不为 null 则返回 true
[ ${b} ]
1 2 3 4 5 6 7
a=hello b=world if [ a = b ]; then echo"string a equal string b" else echo"string a not equal string b" fi
文件测试运算符
文件测试运算符
说明
举例
-b
检测文件是否是块设备文件,如果是,则返回 true
[ -b $file ]
-c
检测文件是否是字符设备文件,如果是,则返回 true
[ -c $file ]
-d
检测文件是否是目录文件,如果是,则返回 true
[ -d $file ]
-f
检测文件是否是普通文件(既不是目录也不是设备文件),如果是,则返回 true
[ -f $file ]
-g
检测文件是否设置了 SGID 位,如果是,则返回 true
[ -g $file ]
-k
检测文件是否设置了粘着位(stucky Bit),如果是,则返回 true
[ -k $file ]
-p
检测文件是否具名管道,如果是,则返回 true
[ -p $file ]
-u
检测文件是否设置了 SUID 位,如果是,则返回 true
[ -u $file ]
-r
检测文件是否可读,如果是,则返回 true
[ -r $file ]
-w
检测文件是否可写,如果是,则返回 true
[ -w $file ]
-x
检测文件是否可执行,如果是,则返回 true
[ -x $file ]
-s
检测文件是否为不为空(文件大小是否不为 0),如果不为 0,则返回 true
[ -s $file ]
-e
检测文件(包括目录)是否存在,如果存在,则返回 true
[ -e $file ]
-a
检测文件(包括目录)是否存在(此命令已废弃),如果存在,则返回 true
[ -e $file ]
1 2 3 4 5 6 7 8 9 10
if [ -e .node ]; then echo'this file is exists' else echo'this file not exists' fi if [ -s .zshrc ]; then echo'file not empty' else echo'file is empty' fi
# 在文件末尾追加三行文本 cat >> file.txt << EOF line 1. line 2. line 3. EOF
# 启动一个 bash 新实例, 并执行提供的脚本, 单引号 EOF 确保脚本内容中的变量不会被提前替换 bash << EOF #!/bin/bash echo "Hello, World!" for i in {1..5}; do echo "Line $i" done EOF
# 连接 mysql 数据库创建表结构并插入两条记录 mysql -u username -p database_name << EOF CREATE TABLE example ( id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL ); INSERT INTO example (name) VALUES ('Tom'), ('Jerry'); SELECT * FROM example; EOF
管道
| 连接两个命令, 第一个命令的输出作为第二个命令的输入
流程
if
1 2 3 4 5 6 7 8 9
# 当 then 单独另写一行时, 分号不能省略 if [-e /root/workspace/test.txt ]; then printf"hello world %s %s\n" $(/bin/date +"%Y-%m-%d %H:%M:%S") # 当 then 单独另写一行时, 分号不能省略 elif [ -s /root/workspace/test.txt ]; then printf"hello world\n" else printf"hello gg\n" fi