适用情况 | |||
1 | if | 分支、多分支 |
if else fi |
2 | for | 范围 |
for do done |
3 | while | 条件 |
while true do exit 0 done |
4 | case | 判断 |
case ) ;; );; *) esac |
1, 接收用户参数
#!/bin/bash
#test
echo "Name of this shell is $0"
echo "Num of pare is $#"
echo "They are $*"
echo "1: $1, 2: $2"
2, if else
#!/bin/bash
#ping
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null
if [ $? -eq 0 ]; then
echo "Host $1 is on-line"
else
echo "Host $1 is off-line"
fi
3, if elif else
#!/bin/bash
read -p "Enter the cord you get: " GRADE
if [ $GRADE -gt 85 ] && [ $GRADE -le 100 ]; then
echo "$GRADE is Perfect"
elif [ $GRADE -gt 70 ] && [ $GRADE -le 85 ]; then
echo "$GRADE is Good"
else
echo "$GRADE is Failed"
fi
4
4.1, for
#!/bin/bash
#for
read -p "Enter the password for new users: " PW
for UN in `cat /root/user.txt`
do
id $UN &> /dev/null
#
if [ $? -eq 0 ]; then
echo
echo "User $UN exists"
echo
else
useradd $UN
echo
echo "$PW" | passwd --stdin $UN
echo
#
id $UN &> /dev/null
if [ $? -eq 0 ]; then
echo
echo "User $UN is created"
echo
else
echo
echo "User $UN is not created"
echo
fi
#
fi
#
done
4.2, for
#!/bin/bash
#for
for UN in $(cat /root/user.txt)
do
id $UN &> /dev/null
#
if [ $? -eq 0 ]; then
userdel -r $UN
else
echo "User $UN does not exist"
fi
#
done
4.3 for
#!/bin/bash
#for
for HN in `cat /root/ip.txt`
do
ping -c 3 -i 0.2 -W 5 $HN &> /dev/null
#
if [ $? -eq 0 ]; then
echo "Host $HN is on-line"
else
echo "Host $HN is off-line"
fi
#
done
5, while
#!/bin/bash
#while
PRC=$(expr $RANDOM % 1000 )
TMS=0
while true
do
read -p "Enter the price you guess: " GUS
let TMS++
#
if [ $GUS -eq $PRC ]; then
echo
echo "Congradulations! The real price is $PRC, you tried $TMS times"
echo
exit 0
elif [ $GUS -lt $PRC ]; then
echo
echo "LOW"
echo
else
echo
echo "HIGH"
echo
fi
#
done
6, case