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
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的和值
[root@localhost ~]# 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、獲取數組長度
[root@localhost ~]# arr_number=(1 2 3 4 5);
[root@localhost ~]# arr_length=${#arr_number[*]}
[root@localhost ~]# echo $arr_length
5
2、讀取某下標賦值
[root@localhost ~]# arr_index2=${arr_number[2]}
[root@localhost ~]# echo $arr_index2
3
3、數組遍歷
[root@localhost ~]# for v in ${arr_number[@]}
do
echo $v
done
1
2
3
4
5
shll基礎,原來腳本並不難!