在使用if作为条件测试时,if取的是后面的条件表达式的状态值,如果不是进行数值比较,则不需要用中括号。
示例1:

[root@Server3 Scripts]# cat test.sh 
#!/bin/bash
read -p "Please input an username: " username
if grep "$username" /etc/passwd &> /dev/null; then
        echo "The User $username is exist"
else
        echo "The User $username is not exist"
fi
[root@Server3 Scripts]# chmod +x test.sh 
[root@Server3 Scripts]# ./test.sh 
Please input an username: frame
The User frame is exist
[root@Server3 Scripts]# ./test.sh 
Please input an username: root
The User root is exist
[root@Server3 Scripts]# ./test.sh 
Please input an username: user1
The User user1 is not exist
[root@Server3 Scripts]#


文件测试

-e FILE:测试文件FILE是否存在。
-f FILE:测试文件FILE是否为普通文件。
-d FILE:测试指定路径是否为目录。
-r FILE:测试指定文件对当前用户来说是否可读。
-w FILE:测试指定文件对当前用户来说是否可写。
-x FILE:测试指定文件对当前用户来说是否可执行。
-b FILE:测试指定文件是否为块设备文件。
-c FILE:测试指定文件是否为字符设备文件。
-h FILE: 测试指定文件是否为链接文件。
-L FILE:测试指定文件是否为链接文件。
-p FILE: 测试指定文件是否为管道文件。
-s FILE: 测试指定文件存在且大小大于0。
-S FILE: 测试指定文件是否为Socket文件。
-u FILE: 测试指定文件是否设置了SUID位。
-g FILE: 测试指定文件是否设置了SGID位。
-k FILE: 测试指定文件是否设置了SBIT位。
file1 -nt file2:file1比file2新时返回真
file1 -ot file2:file1比file2旧时返回真


跟踪脚本执行过程

bash -x 脚本

示例:

[root@Server3 Scripts]# cat uid-gid.sh 
#!/bin/bash
USERNAME=frame
USERGID=$(id -g $USERNAME)
USERUID=$(id -u $USERNAME)
if [ $USERUID -eq $USERGID ];then
        echo "Good Guy"
else
        echo "Bad Guy"
fi
[root@Server3 Scripts]# bash -x uid-gid.sh
+ USERNAME=frame
++ id -g frame
+ USERGID=501
++ id -u frame
+ USERUID=501
+ '[' 501 -eq 501 ']'
+ echo 'Good Guy'
Good Guy
[root@Server3 Scripts]#


位置变量

$0:脚本名称
$1:第一个参数
$2:第二个参数
……
${10}:第十个参数。
shift:位置变量的偏移。

示例:

[root@Server3 Learn]# cat shift.sh 
echo $1
shift
echo $1
shift
echo $1
shift
[root@Server3 Learn]# ./shift.sh a b c
a
b
c
[root@Server3 Learn]# 
说明:shift后面可以跟上数字n,表示的是进行一次位置变量偏移的个数。


特殊变量

$?:命令的退出状态码。
$#:命令行的参数个数。
$*:命令行的参数列表。所有的参数作为一个整体,一个字符串。
$@:命令行的参数列表。每一个参数都是独立的字符串。
$$:脚本的进程ID(PID)。


示例:

[root@Server3 Learn]# cat calc.sh 
#!/bin/bash
if [ $# -ne 2 ];then
        echo "Usage: $0 ARG1 ARG2"
        exit 4
else
        echo "The Sum $1 + $2 is: $(($1+$2))"
        echo "The Sum $1 * $2 is: $(($1*$2))"
fi
[root@Server3 Learn]# sh calc.sh 2 5 
The Sum 2 + 5 is: 7
The Sum 2 * 5 is: 10
[root@Server3 Learn]# sh calc.sh
Usage: calc.sh ARG1 ARG2
[root@Server3 Learn]#