shll基礎,原來指令碼並不難!
------一個小計算器-----
#!/bin/bash
#this
read -p "請輸入第一個整數:" ONE
read -p "請輸入第二個整數:" TWO
read -p "請輸入運算子:" TH
echo "$ONE$TH$TWO=$(($ONE $TH $TWO))"
---------一個IF單分支語句-----
#!/bin/bash
#this
read -p "輸入目錄:" DIR
if [ ! -d $DIR ]
then mkdir -p $DIR
fi
echo "Done"
---------一個IF雙分支語句---
#!/bin/bash
#this
ping -c1 -i0.1 -W1 $1
if [ $? -eq 0 ]
then echo "$1 is UP!"
else echo "$1 is DOWN!"
fi
=================if 巢狀================
#!/bin/bash
#
read -p "請輸入你的成績:" A
if [ $A -le 10 ]
then
echo "恭喜進入決賽"
read -p "請輸入性別(boy/girl):" SEX
if [ $SEX = boy ]
then
echo "進入男子組"
else
echo "進入女子組"
fi
else
echo "很遺憾,你被淘汰"
fi
-------以下是CASE語句----------
#!/bin/bash
#this
export LC_ALL=C //區分大小寫
read -p "請輸入字元:" KEY
case $KEY in
[A-Z] ) echo "您輸入的$KEY是大寫字母。" ;; [a-z] ) echo "您輸入的$KEY是小寫字母。" ;; [0-9] ) echo "您輸入的$KEY是數字。" ;; ,) echo "您輸入的是$KEY。" ;; "#") echo "您輸入的是$KEY。" ;; *) echo "您輸入的是其它字元。" ;;
esac
-----------------以下是函式------------------
#!/bin/bash
sum(){
read -p "請輸入第一個整數:" NUM1
read -p "請輸入第二個整數:" NUM2
echo "你輸入的兩個數為:$NUM1和$NUM2。"
SUM=$(($NUM1+$NUM2))
echo "兩個數的和是:$SUM"
#return $(($NUM1+$NUM2)) //使用返回值的方法,最大不可以大於255
}
sum
#echo "兩個數的和是:$?"
---------以下是FOR迴圈----------------
for IP in 192.168.80.{5..183}
do
ping -c1 -i0.2 -W1 $IP &> /dev/null
if [ $? -eq 0 ]
then echo "$IP is UP!"
else echo "$IP is down!"
fi
done
----------以下是例子------------
#!/bin/bash
#
for USER in test{1..10}
do
useradd $USER
echo "${USER}abc" | passwd --stdin $USER &> /dev/null
done
cat /etc/passwd
-----------以下是WHILE例子-----------
#!/bin/bash
#
i=1
PRE=test
while [ $i -le 10 ]
do
useradd $PRE$i
echo "123" | passwd --stdin $PRE$i &> /dev/null
let i++
done
echo $i
cat /etc/passwd
===================until迴圈語句=====================
##條件不滿足迴圈,一旦滿足則停止##
計算1~50的和值
[[email protected] ~]# vi sum1to50_until_v1.sh
#!/bin/bash
##filename:sum1to50_until_v1.sh
i=0;s=0
until [ $i -eq 50 ]
do
let "i=$i+1";let "s=$s+$i"
done
echo 'sum(1..50)='$s
===========================雙重迴圈==================
#!/bin/bash
#
H=1
while [ $H -le 10 ]
do
L=1
while [ $L -le $H ]
do
echo -n "$L"
let L++
done
echo""
let H++
done
最終輸出:
1
12
123
1234
12345
123456
1234567
12345678
123456789
12345678910
===================shell 陣列========================
Shell陣列
1、獲取陣列長度
[[email protected] ~]# arr_number=(1 2 3 4 5);
[[email protected] ~]# arr_length=${#arr_number[*]}
[[email protected] ~]# echo $arr_length
5
2、讀取某下標賦值
[[email protected] ~]# arr_index2=${arr_number[2]}
[[email protected] ~]# echo $arr_index2
3
3、陣列遍歷
[[email protected] ~]# for v in ${arr_number[@]}
do
echo $v
done
1
2
3
4
5