#!/bin/bash # if [ ! –e /tmp/abc ]; then mkdir /tmp/abc fi
#!/bin/bash # if [ –e /tmp/abc ]; then echo “abc is exits.” else mkdir /tmp/abc echo “Create success.” fi
例:#!/bin/bash # USERID=`id –u user1 ` if [ $USERID –eq 0 ]; then echo “Admin” elif [ $USERID –ge 1 –a $USERID –le 499 ]; then encho “System” else echo “Common user” fi
if 条件1;then if 条件2;then statement fi else statement fi
8、for循环
if [ -e FILE ];then if [ -f FILE ];then echo “Common.” elif [ -d FILE ];then echo “Directory.” else echo “Uknown.” fi else echo “Its not exits.” fi
for 变量(用于赋值的,一定不要加$符) in 列表;do statement1 statement2 … done
例:SUM=0 for I in 1 2 3 4 5 6 7 8;do SUM=$[$SUM+$I] done echo $SUM
9、while循环:在条件满足时进入循环,直到条件不满足时退出;
例:用for循环实现从1到1000之和 declare –i SUM=0 for I in {1…1000};do SUM=$[$SUM+$I] done echo $SUM 例: ping 192.168.0.1到0.20主机是否联通 for I in `seq 1 20`;do ping 192.168.0.$I done
10、case语句,用来替换多分支if语句;
while 条件;do 循环体 done 例:1到100所有整数之和: declare –i SUM=0 declare –I COUNT=1 while [ $COUNT –le 100 ];do SUM=$[$SUM+$COUNT] let COUNT++ done 例:100以内所有偶数之和 declare -i SUM=0 declare -i COUNT=2 while [ $COUNT –le 100 ];do SUM=$[$SUM+$COUNT] let COUNT=$[$COUNT+2] done
case $变量 in 取值1) 语句 ;; 取值2) 语句 ;; 取值3) 语句 ;; *) 语句 ;; esac
11、until循环:与while循环是取反的关系;
- #!/bin/bash
- #
- read -p "A char:" CHAR
- case $CHAR in
- [a-z]
- echo "Char."
- ;;
- [0-9]
- echo "Digit."
- ;;
- ?)
- echo "Others."
- esac
- until 条件;do
- 循环体
- done
12、exit 用于指定结束脚本;
- #!/bin/bash
- #
- declare –i SUM=0
- declare –i I=0
- until [ $I -gt 100 ];do
- let SUM=$[$SUM+$I]
- let I++
- done
- echo $SUM
13、break 停止循环,与exit的区别是exit是退出脚本;
- #!/bin/bash
- #
- read -p "A disk:" DISK
- read -p "Will destroy all data on $DISK, continue?" CHOICE
- if [ "$CHOICE" = 'y' ];then
- dd if=/dev/zero of=$DISK bs=512 count=1 &> /dev/null
- else
- echo "Quit."
- exit
- fi
例:
14、continue 退出当前这一次循环,而提前进入下一次循环;
- #!/bin/bash
- #
- declare -i I=0
- while true;do
- sleep 2
- let I++
- [ $I -eq 5 ] && break
- done
- echo $I
例:1到100之内的偶数之和;
15、脚本的函数 是独立的功能模块,主要是为了实现代码重用;
- #!/bin/bash
- #
- let SUM=0
- let I=1
- while [ $I -le 100 ];do
- if [ $[$I%2] -eq 1 ];then
- let I++
- continue
- fi
- SUM=$[$SUM+$I]
- let I++
- done
- echo $SUM
bash中定义函数的方法:
- 方式一:
- function FUNC_NAME {
- body
- }
- 方式二:
- FUNC_NAME() {
- body
- }
- 例:
- #!/bin/bash
- #
- showecho() {
- echo “How are you!”
- }
- for I in {1..10};do
- showecho
- done
- #!/bin/bash
- #
- JUSER () {
- if id -u root &> /dev/null;then
- return 0
- else
- return 1
- fi
- }
- JUSER &> /dev/null
- echo $?
- #!/bin/bash
- #
- SUM(){
- local SUMARY=0
- SUMARY=$[$1+$2]
- echo $SUMARY
- }
- SUM 5 6
- #!/bin/bash
- #
- SUM () {
- local SUMARY=0
- SUMARY=$[$1+$2]
- echo $SUMARY
- }
- for I in {1..100};do
- SUM $I 1000
- done