编写一个menu的shell脚本程序,执行后的界面为: Number Name For Linux Menu 1 exit leave menu or return 2 menu goto another local menu 3 vi deit a file 4 mail read a mai l 5 send send mail to someone 6 cal see your calendar . 7 who see who is on the system 8 ls list the fi les in this directory 9 cat display a file on the screen Please enter a number or a name for the action you wish: 要求有清屏功能,能正确地执行各项命令并显示。
时间: 2024-02-10 14:15:39 浏览: 71
linux的shell脚本编程
好的,以下是一个简单的实现:
```bash
#!/bin/bash
# 定义菜单选项数组
options=("exit" "menu" "vi" "mail" "send" "cal" "who" "ls" "cat")
# 定义菜单选项名称数组
names=("leave menu" "goto another local menu" "deit a file" "read a mail" "send mail to someone" "see your calendar" "see who is on the system" "list the files in this directory" "display a file on the screen")
# 定义清屏函数
clear_screen() {
if [[ "$OSTYPE" == "darwin"* ]]; then
clear
else
reset
fi
}
# 显示菜单
show_menu() {
clear_screen
echo "Number Name"
echo "For Linux Menu"
for i in ${!options[@]}; do
echo "$i ${names[$i]}"
done
echo ""
}
# 执行命令
execute_command() {
if [[ "$1" =~ ^[0-9]+$ ]]; then
# 根据数字执行对应的命令
if [[ "$1" -ge 0 && "$1" -lt ${#options[@]} ]]; then
if [[ "$1" -eq 0 ]]; then
# 退出脚本
exit 0
elif [[ "$1" -eq 1 ]]; then
# 进入另一个菜单,这里简单地调用show_menu函数
show_menu
else
# 执行命令
command=${options[$1]}
echo ""
read -p "Please enter the $command: " args
eval "$command $args"
fi
else
# 数字不在菜单选项范围内
echo "Invalid option: $1"
fi
else
# 根据名称执行对应的命令
index=-1
for i in ${!names[@]}; do
if [[ "${names[$i]}" == "$1" ]]; then
index=$i
break
fi
done
if [[ "$index" -ne -1 ]]; then
execute_command $index
else
# 名称不在菜单选项范围内
echo "Invalid option: $1"
fi
fi
}
# 主程序
show_menu
while true; do
read -p "Please enter a number or a name for the action you wish: " option
execute_command $option
read -p "Press ENTER to return to menu..." enter_key
show_menu
done
```
这个脚本定义了两个数组,一个是菜单选项数组,包含了9个命令,另一个是菜单选项名称数组,包含了对应的名称。在show_menu函数中,遍历这两个数组输出菜单。在execute_command函数中,根据输入的数字或名称执行对应的命令。最后,在主程序中循环读取输入,执行命令,并显示菜单。
阅读全文