使用case..in..esac做判断
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/bin/bash
read
-p
"Please make a choice:"
choice
case
$choice
in
"one"
)
echo
"Your choice is one"
;;
"two"
)
echo
"Your choice is two"
;;
"three"
)
echo
"Your choice is three"
;;
*)
echo
"Usage $0{one|two|three}"
;;
esac
|
2.while..do..done循环
1
2
3
4
5
6
|
read
-p
"Please guess a word:"
yn
while
[
"$yn"
!=
"yes"
-a
"$yn"
!=
"YES"
]
do
read
-p
"Wrong!guess again:"
yn
done
echo
-e
"OK,you guess right!"
|
3.until..do..done循环
1
2
3
4
5
|
until
[
"$yn"
==
"yes"
-o
"$yn"
==
"YES"
]
do
read
-p
"Please guess a word:"
yn
done
echo
-e
"OK,you guess right!"
|
4.使用while循环计算1到n的总和
1
2
3
4
5
6
7
8
9
10
|
#!/bin/bash
read
-p
"Please input a number:"
n
i=0
s=0
while
[
"$i"
!=
"$n"
]
do
i= $(($i+1))
s= $(($s+$i))
done
echo
-e
"The total from 1 to $n is $s"
|
5.使用for..do..done循环(已知要进行的循环)
1
2
3
4
|
for
animal
in
cat
dog pig
do
echo
-e
"There are ${animal}"
done
|
6.使用for..do..done抓取每个账户的id
1
2
3
4
5
|
users
=$(
cut
-d
':'
-f1
/etc/passwd
)
for
username
in
$
users
do
id
$username
done
|
7.使用ping测试连续网段主机连通性
1
2
3
4
5
6
7
8
9
10
11
12
|
#!/bin/bash
network=
"10.64.1"
for
sitenu
in
$(
seq
1 100)
do
ping
-c 1 -w 1 ${network}.${sitenu} &>
/dev/null
&& result=0||result=1
if
[
"$result"
== 0 ];
then
echo
-e
"Server ${network}.${sitenu} is UP."
else
echo
-e
"Server ${network}.${sitenu} is DOWN"
fi
done
|