shell控制流结构笔记

  man  test 可以看见这些  
  比较符号:-lt小于 -le小于等于   -gt大于   -ge大于等于  -ne不等于   -eq等于 
            < 小于(需要双括号),如:(("$a" < "$b"))
            <= 小于等于(需要双括号),如:(("$a" <= "$b"))
            > 大于(需要双括号),如:(("$a" > "$b"))
            >= 大于等于(需要双括号),如:(("$a" >= "$b"))  
=或==(需要双括号),如:if [ "$a" == "$b" ]
           -b file            若文件存在且是一个块特殊文件,则为真
           -c file            若文件存在且是一个字符特殊文件,则为真
           -d file            若文件存在且是一个目录,则为真
           -e file            若文件存在,则为真
           -f file            若文件存在且是一个规则文件,则为真
           -g file            若文件存在且设置了SGID位的值,则为真
           -h file            若文件存在且为一个符合链接,则为真
           -k file            若文件存在且设置了"sticky"位的值
           -p file            若文件存在且为一已命名管道,则为真
           -r file            若文件存在且可读,则为真
           -s file            若文件存在且其大小大于零,则为真
           -u file            若文件存在且设置了SUID位,则为真
           -x file            若文件存在且可执行,则为真
           -o file            若文件存在且被有效用户ID所拥有,则为真
   -z string          若string长度为0,则为真
           -n string          若string长度不为0,则为真
           string1 = string2  若两个字符串相等,则为真
           string1 != string2 若两个字符串不相等,则为真
    
if  then else语句:
 if 条件 1
    then 命令1
 elif  条件 2
     then  命令2
 else   
      命令3
 fi 完成
   如果if和then在同一行那命令格式为 if 条件1;then
 eg:
#####vim name.sh
#!/bin/bash
#name.sh
echo -n "Enter you name:"
read NAME
if [ "$NAME" == " " ]; then
   echo "you did not enter you name"
else
   echo "you name is: $NAME"
fi
####保存退出,chmod +x name.sh
#### 运行 ./name.sh
[root@localhost ~]# ./name.sh 
Enter you name:tony (这个名字你是输入的)
you name is: tony
 
eg:copy一个文件,如果文件不存在会提示系统错误的信息,和提示自己给的信息
####vim ifcp.sh
#!/bin/bash
#ifcp.sh
if cp test1.txt myfile.txt; then
   echo "copy is successful"
else
   echo "`basename $0`:no such test1.txt file" >&2
fi
####保存退出,chmod +x ifcp.sh
####运行 ./ifcp.sh  -n (-n参数可以检查脚本是否有语法错误)
[root@localhost ~]# ./ifcp.sh 
cp: cannot stat `test1.txt': No such file or directory
ifcp.sh:no such test1.txt file
 
eg:copy一个文件,文件不存在系统提示的信息不显示在屏幕上,显示提示自己给的信息
####vim ifcp.sh
#!/bin/bash
#ifcp.sh
if cp test1.txt myfile.txt 2>/dev/null; then
   echo "copy is successful"
else
   echo "`basename $0`:no such test1.txt file" >&2
fi
####保存退出,chmod +x ifcp.sh
####运行 ./ifcp.sh
[root@localhost ~]# ./ifcp.sh 
ifcp.sh:no such test1.txt file
 
eg:copy一个文件,文件存在则提示copy is successful
####vim ifcp.sh
#!/bin/bash
#ifcp.sh
if cp 1.txt myfile.txt 2>/dev/null; then
   echo "copy is successful"
else
   echo "`basename $0`:no such test1.txt file" 
fi
####保存退出,chmod +x ifcp.sh
####运行 ./ifcp.sh
[root@localhost ~]# ./ifcp.sh 
copy is successful
[root@localhost ~]# cat myfile.txt 
the end
解释:`bsename $0`值显示当前脚本或命令的名字,$0显示会包括当前脚本或命令的路径
       >&2重定向到标准错误,输出到屏幕上
 
eg:一个if---elif---elif--else的语句, -z的参数不知道是什么意思,自己可以man test查看一下,注意空格和分号,引号
#####vim  ifelse.sh
#!/bin/bash
#ifelse.sh
echo -n "Enter your name:"
read NAME
if [ -z $NAME ] || [ "$NAME" = " " ];then
   echo "you did not enter a name"
elif [ "$NAME" = "root" ];then
   echo "Hello root"
elif [ "$NAME" = "tony" ];then
   echo "Hello tony"
else
   echo "hi,$NAME"
fi
####保存退出,chmod +x ifelse.sh
####运行 ./ifelse.sh
[root@localhost ~]# ./ifelse.sh 
Enter your name:root
Hello root
[root@localhost ~]# ./ifelse.sh 
Enter your name:tony
Hello tony
[root@localhost ~]# ./ifelse.sh 
Enter your name:jie
hi,jie
 
case语句:
   case值 in
   模式1)
      命令1
  ;;
   模式2)
      命令2
  ;;
  esac
   case取值后面必须为单词in,每一模式必须以右括号结束。取值可以为变量或常数,匹配发现取值符合某一模式后,期间
 所有命令开始执行直至;;.模式匹配符合*表示任意字符,?表示任意单字符,[..]表示类或范围中任意字符
 
eg:
######vim case.sh
#!/bin/bash
#case.sh
echo -n "Enter a number from 1 to 3:"
read ANS
case $ANS in
   1)
      echo "you select 1"
      ;;
   2)
     echo "you select 2"
     ;;
   3)
    echo "you select 3"
    ;;
   *)
    echo "`basename $0`:this is not between 1 and 3 ">&2
    exit
    ;;
esac
#####保存退出,chmod + case.sh
####运行 ./case.sh
[root@localhost ~]# ./case.sh 
Enter a number from 1 to 3:1
you select 1
[root@localhost ~]# ./case.sh 
Enter a number from 1 to 3:2
you select 2
[root@localhost ~]# ./case.sh 
Enter a number from 1 to 3:3
you select 3
[root@localhost ~]# ./case.sh 
Enter a number from 1 to 3:5
case.sh:this is not between 1 and 3 
 
for循环:
   for 变量名 in 列表
   do  
         命令1
 命令2
   done  
   当变量值在列表里,for循环即执行一次所有命令,使用变量名访问列表中取值,命令可为任何有效的shell命令和语句,变量名
为任何单词,in列表用法是可选的,如果不用它,for循环使用命令行的位置参数。in列表可以包含替换,字符串和文件名。
 
eg:in后面的参数为一个列表
#####vim for1.sh
#!/bin/bash
#for1.sh
for loop in 1 2 3 4 5
do
   echo $loop
done
####保存退出,chmod +x for1.sh
####运行./for1.sh
[root@localhost ~]# ./for1.sh 
1
2
3
4
5
eg:in后面的参数为一个字符串
#####vim for2.sh
#for2.sh
for loop in "orange red bue grey"
do
  echo $loop“
done
####保存退出,chmod +x for2.sh
####运行./for2.sh
[root@localhost ~]# ./for2.sh 
orange red bue grey
把for2.sh里面的内容for loop in "orange red bue grey"  改成for loop in orange red bue greyz则in后面的分行显示
 
eg:in后面的参数为一个命令,``反引号里面的是系统的命令
#####vim for3.sh
#!/bin/bash
#for3.sh
for jie in `cat myfile.txt`
do
    echo $jie
done
####保存退出,chmod +x for3.sh   
[root@localhost ~]# cat myfile.txt 
the end
[root@localhost ~]# ./for3.sh    
the
end
 
eg:一个for和if结合的列子
####vim for4.sh
 
#!/bin/bash
#for4.sh
echo "zhe li mian end you yi ge end" >myfile.txt
for JIE in `cat myfile.txt`
do
    if [ "$JIE" = "end" ];then
       echo "it is:$JIE"
    else
       echo "it is not end,it is:$JIE"
    fi
done
#####保存退出,chmod +x for4.sh
####运行./for4.sh
[root@localhost ~]# ./for4.sh 
it is not end,it is:zhe
it is not end,it is:li
it is not end,it is:mian
it is:end
it is not end,it is:you
it is not end,it is:yi
it is not end,it is:ge
it is:end
 
until循环:
   until 条件
   do 
       命令1
   命令2
   ...
   done
条件可以为任意测试条件,测试发生在循环末尾,因此循环至少执行一次
 
eg:检查磁盘空间的大小,每隔300s检查磁盘空间,超过指定的数字就发邮件给root用户
######vim until.sh
#!/bin/bash
#until.sh
Part="/home"
LOOK_OUT=`df | grep "$Part" | awk '{print $5}'| sed 's/%//g'`
echo $LOOK_OUT
until [ " $LOOK_OUT" -gt "90" ]
do
   echo "this Filesystem is empty" |mail root
   LOOK_OUT=`df | grep "$Part" | awk '{print $5}'| sed 's/%//g'`
     sleep 300
done   
#####保存退出,chmod +x until.sh
####运行./until.sh
 
while循环:
      while 命令
      do
   命令1
   命令2
   ...
  done
 在while和都之间虽然通常指使用一个命令,但可以放几个命令,命令通常用作测试条件 
 
eg:
######vim while.sh
#!/bin/bash
#while.sh
NAME=name.txt
if [  -e "$NAME"  ];then
      echo -e "zhui jia jin qu yi juhua " >> $NAME
    else
       touch $NAME
      echo -e "zhe ge wen jian shi xin jian de " > $NAME
fi
while read LINE
do
     echo $LINE 
done < $NAME
######保存退出,chmod +x while.sh
####运行 ./while.sh
if [  -e "$NAME"  ]    //判断这个文件有木有,若果有则会追加一句话,没有则会新建一个文件,然后会添加一句话
然后通过循环把他显示输出,如果没有这个文件,运行第一遍则只会出现echo -e "zhe ge wen jian shi xin jian de " > $NAME
这个里面的,如果运行第二遍,则 echo -e "zhe ge wen jian shi xin jian de " > $NAME会显示一次,然后
echo -e "zhui jia jin qu yi juhua " >> $NAME会输入一次,运行第三遍,则echo -e "zhui jia jin qu yi juhua " >> $NAME             
会显示更多遍
 
break控制:
  退出循环,如果是在一个嵌入循环里,可以指定n来跳出循环的个数,
eg:
######vim break.sh
#!/bin/bash
#break.sh
while :
do
     echo -n "Enter any number [  1...5 ]:"
     read  ANS
   case  $ANS in
     1|2|3|4|5)
        echo "Your enter a number between 1 and 5."
        ;;
     *)
        echo "Wrong number,bye."
        break
        ;;
    esac
done
######保存退出,chmod +x break.sh
####运行 ./break.sh
[root@localhost ~]# ./break.sh 
Enter any number [  1...5 ]:1
Your enter a number between 1 and 5.
Enter any number [  1...5 ]:3
Your enter a number between 1 and 5.
Enter any number [  1...5 ]:7
Wrong number,bye.
解释:while : ,while后面接一个: 表示while语句永远为真,用break跳出循环。
 
continue控制:
   跳过循环步
 
eg:
#####vim breakcontinue.sh 
#!/bin/bash
#break.sh
while :
do
     echo -n "Enter any number [  1...5 ]:"
     read  ANS
   case  $ANS in
     1|2|3|4|5)
        echo "Your enter a number between 1 and 5."
        ;;
     *)
        echo -n "Wrong number,continue(y/n?)."
        read IS_CONTINUE
        case $IS_CONTINUE in
             y|yes|Y|Yes)
                 continue;
                 ;;
              *) break
                 ;;
        esac
        ;;
    esac
done
######保存退出, chmod +x breakcontinue.sh 
#####运行, ./breakcontine.sh
[root@localhost ~]# ./breakcontinue.sh 
Enter any number [  1...5 ]:3
Your enter a number between 1 and 5.
Enter any number [  1...5 ]:7
Wrong number,continue(y/n?).y
Enter any number [  1...5 ]:6
Wrong number,continue(y/n?).n   
 
vim check_server.sh
####
#!/bin/bash
echo "this script will to find which service have started"
 
#to find www service
testing=`netstat -tlun | grep ":80"`
if [ -n "$testing" ];then                ##if no null is true
    echo "WWW server has started!"
fi
 
#to find vsftpd service
testing=`netstat -tlun | grep ":21"`
if [ "$testing" != "" ];then            ###if no null is true
    echo "vsftpd server has started!"
fi
 
#to find ssh service
testing=`netstat -tlun | grep ":22"`
if [ -n "$testing" ];then
    echo "SSH server has started!"
fi
 
#to find mail service
testing=`netstat -tlun | grep ":25"`
if [ "$testing" != ""  ];then
    echo "MAIL server has started!"
fi
 
#####
 
 
 
function功能
 
格式:
function fname()
{
  程序段
}
function的设定一定要在程序的最前面
拥有内建变量,$0表示函数名称,后续接的变量标记为$1,$2,$3....
 
vim func.sh
###
#!/bin/bash
function printinfo()
{
    echo "you choice is"
}
case $1 in
    "one")
printinfo;echo $1 | tr -s 'a-z' 'A-Z'
;;
    "two")
        printinfo;echo $1 | tr -s 'a-z' 'A-z'
        ;;
esac  
####
 
 
 
shell脚本实现1+2+...+100
vim sum.sh
####
#!/bin/bash
i=0
s=0
while [ "$i" -lt 100 ]
do
    i=$(($i+1))
    s=$(($s+$i))
done
echo "1+2+3+...+$i=$s"
####   
 
 
vim sum1.sh
####
#!/bin/bash
s=0
for ((i=0;i<=100;i++))
do
    s=$(($s+$i))
done
echo "1+2+..+100=$s"
echo "i=$i"
####
 
for的另一种格式
 
vim for.sh
####
#!/bin/bash
for animal in cat dog pig
do
        case $animal in
                "cat")
                        echo "$animal miao miao jiao"
                        ;;
                "dog")
                        echo "$animal wang wang jiao"
                        ;;
                "pig")
                        echo "$animal luo luo jiao"
                        ;;
                "*")
                        echo "$animal jiao mei jiao"
                        ;;
        esac
done
####
原文地址:https://www.cnblogs.com/sysk/p/4877975.html