概述
写脚本的时候会碰到创建交互式菜单的情况,比如碰到写一个lnmp一键安装脚本的时候会让用户选择安装mysql的版本或者选择安装各种组件,总之在创建菜单是很常见的。
而select是bash的一种扩展应用,让用户可以在一组不同的值中选择,类似下面
This is a menu Test
Please Choose what you want
1) bugger
2) linux:
#?
之后你就输入前面的菜单选择就是了
实例代码
#!/bin/bash
echo "Please select your favorite linux distribution"
linux_distributions="Ubutnu Fedora Centos Arch"
select linux_distribution in $linux_distributions:
do
echo "you selected $REPLY $linux_distribution"
done
上面要注意几个地方,select这个循环内容里面包含的是选择之后要执行的东西REPLY这个变量就是你选择的菜单的号码,其实不难,比如再比如下面
#!/bin/bash
ubuntu(){
echo "This is ubuntu func"
}
fedora(){
echo "This is fedora func"
}
centos(){
echo "This is centos func"
}
arch(){
echo "This is arch func"
}
echo "Please select your favorite linux distribution"
linux_distributions="Ubutnu Fedora Centos Arch"
select linux_distribution in $linux_distributions:
do
case $REPLY in
1) ubuntu
;;
2) fedora
;;
3) centos
;;
4) arch
;;
*) echo "please choose 1-4"
;;
esac
done
执行结果
Please select your favorite linux distribution
1) Ubutnu
2) Fedora
3) Centos
4) Arch:
#? 1
This is ubuntu func
#? 2
This is fedora func
#? 3
This is centos func
#? 4
This is arch func
#? 5
please choose 1-4
#? 6
please choose 1-4
#?
要注意的地方
select可能有的shell会报错,比如zsh
./test.sh: 9: ./test.sh: select: not found
其实只要指定shell去执行就可以
bash + 要执行的脚本
欢迎关注我的博客www.bboy.app
Have Fun