一 条件语句
1.1 if—then
#!/bin/bash
if root
then
echo "hello"
fi
如果命令运行成功(退出码为0),则then部分的命令被执行
1.2 if—then—else
#!/bin/bash
if hunter
then
echo "hello"
else
echo "goodbye"
fi
if语句中退出码非0,则执行else部分语句
1.3 elif
#!/bin/bash
if A
then
echo "nice to meet you"
elif B 多重If判断
then
echo "hello"
fi
1.4 test命令
与其它编程语言思维一样的方式
#!/bin/bash
if test 1 -eq 2 test命令列出条件成立则退出并返回状态码0,命令等同if [ 1 -eq 2]
then
echo "right"
else
echo "wrong"
fi
二 条件比较
2.1 数据比较
n1 -eq n2 相等
n1 -ge n2 大于或等于
n1 -gt n2 大于
n1 -le n2 小于等于
n1 -lt n2 小于
n1 -ne n2 不等于
2.2 字符串比较
str1 = str2
str1 != str2
str1 < str2
str1 > str2
-n str1 检查str1的长度是否非0
-z str1 检查str1的长度是否为0
#!/bin/bash
str1=good
str2=wrong
if [ $str1 \> $str2 ] 大于号需要转义,否则脚本会当重定向符号
then echo "$str1 is greater than $str2"
else
echo "$str1 is less than $str2"
fi
#!/bin/bash
str=
if [ -z "$str" ] 判断字符串是否为空,空的或未初始化的变量对Shell脚本很致命
then
echo "empty"
else
echo "not empty"
fi
2.3 文件比较
item1 | item2 | 含义 |
---|---|---|
-d | file | 检查文件是否存在且为目录 |
-e | file | 检查文件是否存在 |
-f | file | 检查文件是否存在且为文件 |
-r | file | 检查文件是否存在且可读 |
-s | file | 检查文件是否存在且非空 |
-w | file | 检查文件是否存在且可写 |
-x | file | 检查文件是否存在且可执行 |
-O | file | 检查文件是否存在且属当前用户 |
-G | file | 检查文件是否存在且默认组与当前用户相同 |
Item1 | 含义 |
---|---|
file1 -nt file2 | 检查file1是否新于file2 |
file1 -ot file2 | 检查file1是否旧于file2 |
2.4 复合条件—>&&与、||或
#!/bin/bash
if [ -e str ] && [ -f zero ]
then
echo "file all exist"
fi
2.5 双圆括号
#!/bin/bash
str1=good
str2=wrong
if (( $str1 > $str2 )) 双圆括号中表达式里的大于号不用转义
then echo "$str1 is greater than $str2"
else
echo "$str1 is less than $str2"
fi
2.6 双方括号
#!/bin/bash
if [[ $USER == r* ]] 支持通配符模式
then
echo "welcome root user"
else
echo "sorry"
fi
2.7 case分支
#!/bin/bash
case $USER in
root|hunterno4)
echo "welcome root user";; 尾部两个分号
mysql)
echo "welcome to database";;
surfftp)
echo "nice to meet you";;
*) 都不匹配时的default语句
echo "i don't know you";;
esac
三 循环语句
3.1 for循环
#!/bin/bash
for command in `ls /bin` for循环默认每个值以空格来分割
do
echo "command in /bin is $command"
done
#!/bin/bash
for file in /usr/local/program/package/*
do
if [ -d "$file" ] 文件用引号圈起,以避免文件含空格等情况
then
echo "$file is a directory"
elif [ -f "$file" ]
then
echo "$file is a file"
fi
done
3.2 字段分隔符
#!/bin/bash
IFS.OLD=$IFS
IFS=$'\n' 修改IFS分隔符为换行符,也可同时赋值为:;"等等
for str in `cat /home/hunterno4/passwd`
do
echo "str in passwd is $str"
done
IFS=$IFS.OLD 恢复IFS分隔符默认值
3.3 C语言风格的for循环
#!/bin/bash
for ((i = 0;i<5 ;i++)) 此时变量与值间可以有空格,变量不用加$号
do
echo "current number is $i"
done
3.4 while命令
#!/bin/bash
i=5
while [ $i -gt 0 ]
do
echo $i
i=$[ $i-1 ]
done
3.5 嵌套循环
#!/bin/bash
IFS.OLD=$IFS
IFS=$'\n'
for row in `cat /etc/passwd`
do
echo "passwd row in $row ———"
IFS=$':'
for words in $row
do
echo " $words"
done
done
IFS=$IFS.OLD
4 循环控制
4.1 break
#!/bin/bash
i=5
while [ $i -gt 0 ]
do
echo $i
i=$[ $i-1 ]
if [ $i -eq 3 ]
then
break 自动终止最里面的循环,break n,终止n层循环
fi
done
4.2 continue
#!/bin/bash
i=10
while [ $i -gt 0 ]
do
i=$[ $i-1 ]
if [ $i -gt 3 ] && [ $i -lt 6 ]
then
continue continue n则指定继续执行哪级循环
fi
echo "$i"
done > output.txt 将循环过程中的结果重定向输出到文件