使用shell创建一个简单的菜单bash select用法

概述

写脚本的时候会碰到创建交互式菜单的情况,比如碰到写一个lnmp一键安装脚本的时候会让用户选择安装mysql的版本或者选择安装各种组件,总之在创建菜单是很常见的。

而select是bash的一种扩展应用,让用户可以在一组不同的值中选择,类似下面

1
2
3
4
5
This is a menu Test
Please Choose what you want
1) bugger
2) linux:
#?

之后你就输入前面的菜单选择就是了

实例代码

1
2
3
4
5
6
7
8
9
10
#!/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这个变量就是你选择的菜单的号码,其实不难,比如再比如下面

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#!/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

执行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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 + 要执行的脚本

欢迎关注Bboysoul的博客www.bboysoul.com
Have Fun