一,shell的控制结构
1,if
if【空格】【空格expresion空格】
then
命令1
elif 条件2
then
命令2
else
命令3
fi
---------------------
if 条件
then
命令
fi
--------------------
$ cat if.sh
#!/bin/bash
### test if
if [ "13" -lt "12" ] # test [空格expresion空格]
then
echo "10 is less than 12"
else
echo "no"
fi
-----------------------------------
man test查看if条件参数信息
-----------------------------------
$ cat ifcp.sh
#!/bin/bash
### if cp test
if cp file1.txt file2.txt
then
echo "successful"
else
echo "'bash $0' fail" >&2
fi
2,case
case 值 in
模式1)
命令1
;;
模式2)
命令2
;;
esac
-----------------------------------
$ cat case.sh
#!/bin/bash
###case test
echo "input 1 -3:"
read choose
case $choose in
1)
echo "you choose 1."
;;
2)
echo "you choose 2"
;;
3)
echo "you choose 3"
;;
*)
echo "$0 - your choose out of 1-3">&2
exit;
;;
esac
3,for
for 变量 in 列表
do
命令1
...
命令n
done
------------------------------
$ cat for.sh
#!/bin/bash
### for test
for i in 1 2 3 4 5
do
echo $i
done
---------------------------------
$ cat strfor.sh
#!/bin/bash
### string for test
for str in `cat name.txt`
do
echo $str
done
4,until
$ cat until.sh
#!/bin/bash
### until test
pathvar='/dev/sda1'
lookup=`df -h|grep $pathvar|awk '{print $5}'|sed 's/%//g'`
echo $lookup
until [ "$lookup" -gt "90" ]
do
echo "$pathvar is available"
lookup=`df -h|grep $pathvar|awk '{print $5}'|sed 's/%//g'`
sleep 60
done
5,while
死循环
while :
do
命令...
done
6,引用,统计
sum=0
for i in `cat $1`
do
let sum=sum+$i
done
echo $sum