Linux Shell 语言得一些基本语法。

Shell语法

If语句格式

(number=num)

read -p "请输入一个数字" num 

       if [ $num -eq 3 ]   (如果)

then

      echo "wo xiang ni"

elif [ $num -le 5 ]

     then (然后)

     echo "zhen xiang le "

else [ $num -ge 6 ] (否则)

      echo "miss 531"

fi  (结束)

闰年

第一版

year=`date +%Y`

if [ $[ $year % 400 ] -eq 0 ]

then

echo "$year is a leap year."

elif [ $[ $year % 4 ] -eq 0 ]

then

if [ $[ $year % 100 ] -ne 0 ]

then

echo "$year is a leap year."

else

echo "$year is not a leap year."

fi

else

echo "$year is not a leap year."

fi

第二版(原版)

year=$(date +%Y)

if [ $[ $year % 400 ] -eq 0 ]

then

echo "$year is a leap year."

elif [ $[ $year % 4 ] -eq 0 ]

then

if [ $[ $year % 100 ] -ne 0 ]

then

echo "$year is a leap year."

else

echo "$year is not a leap year."

fi

else

echo "$year is not a leap year."

fi

第三版(查询哪一年是闰年)

read -p "shu ru nian fen" year

if [ $[ $year % 400 ] -eq 0 ]

then

echo "$year is a leap year."

elif [ $[ $year % 4 ] -eq 0 ]

then

if [ $[ $year % 100 ] -ne 0 ]

then

echo "$year is a leap year."

else

echo "$year is not a leap year."

fi

else

echo "$year is not a leap year."

fi

FOR 循环

格式语法:for NAME in [ LIST ];do COMMANDS; done

​ 列表 执行命令 结束

LIST用法

直接写 1 2 3
大括号 {1..5}
文件名 /etc/*.conf
命令结果 find /etc/ -name “*.conf”
C语言风格 for ((i=0;i<5 i=i+2))
i++

ping网段案例

ping.sh

for p in {1..10}    p---变量名称

do   do----执行内容

host=(192.168.18.$p)

ping -c2 192.168.18.$p >> /root/Desktop/2.txt  c2---频率

if [ $? == 0 ]

then

echo "$host is online."     在线

else

echo "$host is offline."   不在线

fi

done

while循环

aa=1

while [ $aa -le 10 ]

do

echo "wo xiang ni le"

aa=$[$aa+1]

done

case 判断

aa=3      ( 3 变量值)

case "$aa" in   

    1)

     echo "haha";;  (1,2,4常量值)

    2)

     echo "heihei";;

    3)

     echo "nimei";; (有内容两;没有一个;)

esac

break

终止当前for循环

for n in {1..10}

do

        if [ $n -eq 3 ]

        then

                break

        fi

        echo $n

done

continue

跳出本次循环

for n in {1..10}

do

        if [ $n -eq 3 ]

        then

               continue

        fi

        echo $n

done

评论