*编辑更新状态
我正在尝试制作一个 bash 文件,让您可以选择一个选项,输出答案,然后循环回到菜单选择。截至目前,我拥有的代码是:
#!/bin/sh
echo off
echo "........................................."
echo "Select the process you would like to run."
echo.
echo "1 - Free Disk Space Available"
echo "2 - List Directories"
echo "3 - Show Running Processes"
echo "4 - TCP Connection"
echo "5 - Network Interfaces"
echo "6 - List Directories"
echo "7 - Show Computer Hostname"
echo "8 - Routing Table"
echo "9 - Computer Uptime"
echo "10 - Available Block Devices"
echo "11 - Mount Device"
echo "........................................."
echo -n "Input desired function number and press ENTER: "
read selection
while [ {selection} ]
do
if [ $selection == 1 ]; then echo df -h
break
elif [ $selection == 2 ]; then echo ls -l /home
break
elif [ $selection == 3 ]; then echo ps -A
break
elif [ $selection == 4 ]; then echo netstat -a
break
elif [ $selection == 5 ]; then echo ifconfig
break
elif [ $selection == 6 ]; then echo $PATH
break
elif [ $selection == 7 ]; then echo hostname
break
elif [ $selection == 8 ]; then echo route
break
elif [ $selection == 9 ]; then echo uptime
break
elif [ $selection == 10 ]; then echo blkid
break
elif [ $selection == 11 ]; then echo mount
break
else
echo "Please enter a valid option"
fi
done
我得到的输出是一个无限循环的错误
[: 2: unexpected operator
如果有人能帮助我或指导我朝着正确的方向前进,我将不胜感激。
最佳答案
对于菜单,使用select
命令。在这里,我使用 bash
将选项存储到一个数组中。
#!/bin/bash
echo ".............................................................................."
echo "Select the process you would like to run by pressing the corresponding number."
choices=(
"Free Disk Space Available"
"List Directories"
"Show Running Processes"
"TCP Connection"
"Network Interfaces"
"List Directories"
"Show Computer Hostname"
"Routing Table"
"Computer Uptime"
"Available Block Devices"
"Mount Device"
)
PS3="Input desired function number and press ENTER: "
select selection in "${choices[@]}"
do
case "$selection" in
"${choices[0]}" ) echo df -h ;;
"${choices[1]}" ) echo ls -l /home ;;
"${choices[2]}" ) echo ps -A ;;
"${choices[3]}" ) echo netstat -a ;;
"${choices[4]}" ) echo ifconfig ;;
"${choices[5]}" ) echo $PATH ;;
"${choices[6]}" ) echo hostname ;;
"${choices[7]}" ) echo route ;;
"${choices[8]}" ) echo uptime ;;
"${choices[9]}" ) echo blkid ;;
"${choices[10]}" ) echo mount ;;
esac
done
如果你想跳出菜单,你会这样做
"${choices[10]}" ) echo mount; break ;;
或者添加一个“退出”选项
关于linux - 使用循环菜单创建 Bash 文件 (Linux),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46453114/