------一个小计算器-----
#!/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的和值
[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