exit:退出脚本
exit 错误码
[root@bogon ~]# nano exitshtest.sh
You have new mail in /var/spool/mail/root
[root@bogon ~]# chmod +x exitshtest.sh
[root@bogon ~]# ./exitshtest.sh
no such user: user1.
GNU nano 2.0.9 File: exitshtest.sh
#!/bin/bash
#
USERNAME=user1
if ! grep "^$USERNAME\>" /etc/passwd &> /dev/null; then
echo "no such user: $USERNAME."
exit 1
fi
echo "welcome "
整数测试:-gt、-le、-ne、-eq、-ge、-lt
[ expression ]、[[expression]]、test expression
文件测试
-e FILE:测试文件是否存在
-f FILE :测试文件是否为普通文件
-d FILE:测试指定路径是否为目录
-r FILE:测试当前用户对指定文件是否有读权限
-w FILE:测试当前用户对指定文件是否有写权限
-x FILE:测试当前用户对指定文件是否有执行权限
[root@bogon /]# [ -e /etc/inittab1 ]
[root@bogon /]# echo $?
1
[root@bogon /]# [ -e /etc/inittab ]
[root@bogon /]# echo $?
0
多分支if语句:
if 判断条件1;then
statement1
...
elif 判断条件2;then
statement2
...
else
statement3
...
fi
测试脚本是否有语法错误:
bash -n FILE
bash -x FILE 单步调试
bash变量的类型
本地变量(局部变量)
环境变量
位置变量:$1,$2,.......,shift
特殊变量:$?(执行结果) $#(参数个数) $*(参数列表) $@(参数列表)
./filetest.sh /etc/fstab /etc/inittab
$1为: /etc/fstab
$2为:/etc/inittab
利用$1变量传输:
#!/bin/bash
#
if [ -e $1 ];then
echo "ok"
else
echo "no such file"
fi
[root@bogon ~]# nano filetest.sh
You have new mail in /var/spool/mail/root
[root@bogon ~]# chmod +x filetest.sh
[root@bogon ~]# ./filetest.sh /etc/inittab
./filetest.sh: line 3: [-e: command not found
no such file
[root@bogon ~]# bash -x filetest.sh
+ '[-e' ']'
filetest.sh: line 3: [-e: command not found
+ echo 'no such file'
no such file
[root@bogon ~]# nano fi
file-2016-11-09-04-09-42.txt filetest.sh first.sh
[root@bogon ~]# nano filetest.sh
[root@bogon ~]# ./filetest.sh /etc/inittab
ok
[root@bogon ~]# ./filetest.sh /etc/initta
no such file
[root@bogon ~]# nano filetest.sh
[root@bogon ~]# ./filetest.sh /etc/initta /etc/fstab
2
/etc/initta /etc/fstab
/etc/initta /etc/fstab
no such file
[root@bogon ~]# nano filetest.sh
[root@bogon ~]# ./filetest.sh /etc/inittab /etc/fstab
2
/etc/inittab /etc/fstab
/etc/inittab /etc/fstab
ok
#!/bin/bash
#
echo $#
echo $*
echo $@
if [ -e $1 ];then
echo "ok"
else
echo "no such file"
fi
利用shift轮询变量$1:
[root@bogon ~]# nano filetest1.sh
[root@bogon ~]# ./filetest1.sh 1 2 3 4
1
2
3
[root@bogon ~]#
#!/bin/bash
#
echo $1
shift
echo $1
shift
echo $1