2、脚本退出
#一个执行成功的脚本返回值为0,不成功为非0
[root@localhost script]# clear
[root@localhost script]# sh hello.sh
hello world,i am coming
11
[root@localhost script]# echo $?
0
#判断一个目录内是否有某个文件,有则回显file exsit ,没有则返回1
[root@localhost script]# cat test.sh
#! /bin/bash
cd /home
if [ -f file ];then
echo "file exsit"
else
exit 2
fi
[root@localhost script]# sh test.sh
[root@localhost script]# echo $?
2
[root@localhost script]#
3、Test语句、if语句
test -d xx 目录是否存在
test -f xx 文件是否存在
test -b xx 是否为块文件
test -x xx 是否为可执行文件
A -eq B 判断是否相等
A -ne B 判断不相等
A -le B 小于等于
A -lt B 小于
A -gt B 大于
#if条件判断语句
if [];then
......
else
......
fi
#if语句嵌套
if [];then
.......
elif [];then
.......
elif [];then
.......
else
......
fi
#test举例,判断test文件是否存在,如果存在对其进行备份操作。如果不在回显信息
#例子:输入一个数值判断其在哪个区间。小于80,大于100,位于80到100之间,用的是if嵌套!
[root@localhost script]# cat if.sh
#! /bin/bash
read -p "plz input a $num:" num
if [ $num -le 80 ];then
echo "num is less 80"
elif [ $num -ge 80 ] && [ $num -le 100 ];then
echo "num between 80 and 100"
else
echo "num is greater than 100"
fi
4、循环语句 for、while
for var in $var1 $var2 $var3 var4... $var
do
......
......
done
#例子:打印1到10数字
[root@localhost home]# cat for1.sh
#! /bin/bash
for var in {1..10}
do
echo "$var"
sleep 2
done
[root@localhost home]# sh for1.sh
1
2
3
4
5
6
7
8
9
10
[root@localhost home]#
#打印方块内容 for嵌套
[root@localhost home]# sh for2.sh
*********
*********
*********
*********
*********
*********
*********
*********
*********
[root@localhost home]# cat for2.sh
#! /bin/bash
for ((i=1;i