任务1:猜数字游戏,随机生成一个1-100的数字,如果猜到了就提示正确,并结束,如果猜大了,就提示大了,猜小了就提示小了,直到猜对为止。
解析:首先需要生成一个1-100的随机数,然后让用户输入猜测的数字,根据用户输入的数字给出提示,直到猜对为止。
代码:
```bash
#!/bin/bash
echo "猜数字游戏开始!"
echo "请输入一个1-100之间的整数:"
read num
random_num=$((RANDOM % 100 + 1))
while [ $num -ne $random_num ]
do
if [ $num -gt $random_num ]
then
echo "猜大了!"
elif [ $num -lt $random_num ]
then
echo "猜小了!"
fi
echo "请输入一个1-100之间的整数:"
read num
done
echo "恭喜你猜对了!"
```
任务2:用户输入三个数字,返回结果按从小到大排列.
解析:需要获取用户输入的三个数字,然后使用排序命令将它们按照从小到大的顺序排列。
代码:
```bash
#!/bin/bash
echo "请输入三个数字:"
read a b c
arr=($a $b $c)
IFS=$'\n' sorted=($(sort -n <<<"${arr[*]}"))
unset IFS
echo "从小到大排序后的结果为:${sorted[@]}"
```
任务3:石头剪刀布游戏。
解析:需要实现一个简单的石头剪刀布游戏,有两种模式一种为3局两胜模式,一种为5局3胜模式,用户首先选择模式,后用户输入自己的选择,计算机随机选择,然后判断胜负。
代码:
#!/bin/bash
function get_computer_choice {
choices=("石头" "剪刀" "布")
computer_choice=$((RANDOM % 3))
echo "${choices[computer_choice]}"
}
function determine_winner {
user_choice=$1
computer_choice=$2
if [[ $user_choice == $computer_choice ]]; then
echo "平局!"
elif [[ ($user_choice == "石头" && $computer_choice == "剪刀") ||
($user_choice == "剪刀" && $computer_choice == "布") ||
($user_choice == "布" && $computer_choice == "石头") ]]; then
echo "你赢了!"
user_wins=$((user_wins + 1))
else
echo "计算机赢了!"
computer_wins=$((computer_wins + 1))
fi
}
function play_game {
echo "选择游戏模式:"
echo "1. 3局两胜模式"
echo "2. 5局3胜模式"
read -p "请输入模式编号: " game_mode
if [[ $game_mode -eq 1 ]]; then
max_rounds=3
max_wins=2
elif [[ $game_mode -eq 2 ]]; then
max_rounds=5
max_wins=3
else
echo "无效的模式编号!"
return
fi
user_wins=0
computer_wins=0
rounds_played=0
echo "游戏开始!"
echo
while [[ $rounds_played -lt $max_rounds && $user_wins -lt $max_wins && $computer_wins -lt $max_wins ]]; do
echo "第 $((rounds_played+1)) 轮"
read -p "请输入你的选择(石头/剪刀/布): " user_choice
if [[ $user_choice != "石头" && $user_choice != "剪刀" && $user_choice != "布" ]]; then
echo "无效的选择!"
continue
fi
computer_choice=$(get_computer_choice)
echo "计算机选择了: $computer_choice"
determine_winner "$user_choice" "$computer_choice"
rounds_played=$((rounds_played + 1))
echo
done
echo "游戏结束!"
if [[ $user_wins -gt $computer_wins ]]; then
echo "你赢得了游戏!"
elif [[ $user_wins -lt $computer_wins ]]; then
echo "计算机赢得了游戏!"
else
echo "游戏结束,没有赢家!"
fi
}
play_game
遇到的问题:中文输入修改
参考:linux中修改中文输入
任务4:测试192.168.4.0网段,哪些主机是开机状态。
解析:需要使用ping命令测试192.168.4.0网段的主机是否开机。
代码:
```bash
#!/bin/bash
echo "正在测试192.168.4.0网段的主机..."
for i in {1..254}
do
ip="192.168.4.$i"
result=$(ping -c 1 -W 1 $ip | grep "received" | awk '{print $4}')
if [ "$result" == "1" ]
then
echo "$ip 是开机状态"
fi
done
```
任务5:显示网卡的数据包流量
解析:需要使用ifconfig命令查看网卡的数据包流量。
代码:
```bash
#!/bin/bash
echo "显示网卡的数据包流量:"
ifconfig | grep -E "^eth|^wlan" | awk '{print $1, $2, $3, $4, $5}'
```