条件判断语句
if elif else
if 条件 ; then shell命令
fi
if 条件
then shell命令
fi
if 条件
then shell命令
else
shell命令
fi
if [ $1 -eq 1 ]
then echo "A"
elif [ $1 -eq 2 ]
then echo "B"
elif [ $1 -eq 3 ]
then echo "C"
else
echo "D"
fi
case $1 in
1) echo "A";;
2) echo "B";;
3) echo "C";;
*) echo "D";;
esac
case选择
case 变量引用 in
模式1) shell命令;;
模式2) shell命令;;
*) shell命令;;
……
esac
case行尾必须为单词 in 每个模式必须以右括号 ) 结束
双分号 ;; 表示命令序列结束
模式不支持正则,支持glob
case语句结构特点如下:
匹配模式中可是使用方括号表示一个连续的范围,如[0-9];使用竖杠符号“|”表示或。
最后的“*)”表示默认模式,当使用前面的各种模式均无法匹配该变量时,将执行“*)”后的命令序列。
for循环
for 变量名 in 列表; do
循环体
done
列表生成方案:
(1)使用空格分割的列表
循环添加三个用户并设置密码:
for username in user1 user2 user3;do
if id $username &> /dev/null
then echo "用户已经存在"
else
useradd $username
if [ $? -eq 0 ]
then echo "$username"|passwd --stdin $username &>/dev/null
fi
fi
done
(2)一般整数列表 {开始..结束}
for i in {1..10};do
echo "参数$i"
done
(3)seq整数列表 $(seq [开始 [步长]] 结束)
for i in $(seq 2 2 10);do
echo "$i"
done
(4)返回列表的命令
例如:ls /var
for file in $(ls) ;do
if [ -f $file ]
then echo "普通文件$file"
elif [ -d $file ]
then echo "目录$file"
else
echo "其他文件$file"
fi
done
(5)使用glob通配
列出当前目录下文件的类型
for file in * ;do
if [ -f $file ]
then echo "普通文件$file"
elif [ -d $file ]
then echo "目录$file"
else
echo "其他文件$file"
fi
done
列出/var目录下文件的类型
for file in /var/* ;do
if [ -f $file ]
then echo "普通文件$file"
elif [ -d $file ]
then echo "目录$file"
else
echo "其他文件$file"
fi
done
(6)使用$@
循环输出输入参数:
for var in $@; do
echo $var
done
while循环
while 条件 ;do
循环体
done
打印0-19
count=0;
while [ $count -lt 20 ];do
echo "$[count++]"
done
1到100求和
count=1;
sum=0;
while [ $count -le 100 ];do
let sum+=$[count++];
done
echo $sum
until循环
until 条件;do
循环体
done
条件为false ,进入循环
条件为true,退出循环
1到100求和
count=1;
sum=0;
until [ $count -gt 100 ];do
let sum+=$[count++];
done
echo $sum
循环控制语句
continue
break
[ 0 ] 和 true等价
while [ 0 ] ;do
read -p "请输入一个字符串,输入exit结束" input
if [ $input == "continue" ]
then continue
elif [ $input == "exit" ]
then exit
else
echo $input
fi
done
until false ;do
read -p "请输入一个字符串,输入exit结束" input
if [ $input == "continue" ]
then continue
elif [ $input == "exit" ]
then exit
else
echo $input
fi
done
while的特殊用法:遍历文件
遍历文件test1.sh 每一秒输出一行
while read line;do
echo $line
sleep 1
done < test1.sh
for循环特殊用法
循环输出0-9
for((i=0;i<10; i++));do
echo $i
done
打印99乘法表
for((i=1;i<=9; i++));do
for((j=1;j<=i;j++));do
echo -n "$i*$j=$[i*j] "
done
echo
done