1 需求分析

Linux shell编程学习笔记21:用select in循环语句打造菜单


中,我们利用select in循环语句打造的菜单中,菜单项都是用系统设置的颜色配置来显示的。
为了让菜单更美观,我们想让每个菜单项分别以不同的颜色来显示,要如何实现呢?

2 打造彩色的选项菜单的方法

  1. 首先,我们把要显示的菜单项保存到一个数组中
  2. 然后,我们用循环语句 for in 来显示数组中的菜单项,在显示菜单时我们可以为每个菜单项加上一个数字序号作为选择该菜单的数字,并利用\e[xm (其中x的值为31-37)来实现彩色显示
  3. 接着,我们用read命令读取用户输入的数值。
  4. 最后,对用户输入的数值进行判断,并做相应的处理。

3 演示代码

我们显示一个水果菜单,并增加一个exit菜单选项

当用户输入数字n后,我们进行判断:

如果n 为水果菜单选项对应的数字,显示相应的水果

如果n为exit菜单选项的数字,显示用户选择了退出选项

否则,显示用户输入了错误的数字。

代码如下:

f=(apple banana orrange peach);# 定义水果数组
c=31;   # 颜色
o=1;    #序号
for i in $f;do
     echo -e "\e[${c}m $o)$i \e[0m"; #用不同颜色显示水果选项
     let c+=1;
     if [[ $c > 37 ]]; then
         $c=31;
     fi;
     let o+=1;
done;
     
echo " $o)exit"; # 显示 退出 选项

echo -n "enter the number before the fruit your liked(1 - ${#f}):"; #提示用户输入选项前的数字
read s; #读取用户输入的字符并存入s

if [[  $s -gt 0 && $s -le ${#f} ]]; then #用户输入的是水果选项
   let c=30+s;       #计算水果选项对应的颜色
   echo -e "You selected \e[${c}m$f[$s]\e[0m";#显示用户选择的水果选项
elif [[ $s -eq ((${#f}+1)) ]]; then # 用户选择的是退出选项
   echo You selected exit;#显示用户选择了退出选项
else
   echo Your enter a error number;#显示用户输入的错误的数字
fi

3.1 创建 脚本文件a.sh

 用cp 命令来创建脚本文件,文件内容输入完后按Ctrl+D结束文件输入。

purpleEndurer @zsh $ cp /dev/stdin a.sh         
 f=(apple banana orrange peach);# 定义水果数组
 c=31;   # 颜色
 o=1;    #序号
 for i in $f;do
      echo -e "\e[${c}m $o)$i \e[0m"; #用不同颜色显示水果选项
      let c+=1;
      if [[ $c > 37 ]]; then
          $c=31;
      fi;
      let o+=1;
 done;
      
 echo " $o)exit"; # 显示 退出 选项echo -n "enter the number before the fruit your liked(1 - ${#f}):"; #提示用户输入选项前的数字
 read s; #读取用户输入的字符并存入sif [[  $s -gt 0 && $s -le ${#f} ]]; then #用户输入的是水果选项
    let c=30+s;       #计算水果选项对应的颜色
    echo -e "You selected \e[${c}m$f[$s]\e[0m";#显示用户选择的水果选项
 elif [[ $s -eq ((${#f}+1)) ]]; then # 用户选择的是退出选项
    echo You selected exit;#显示用户选择了退出选项
 else
    echo Your enter a error number;#显示用户输入的错误的数字
 fi 
 purpleEndurer @zsh $

Linux shell编程学习笔记30:打造彩色的选项菜单_学习笔记

3.2  执行和测试脚本

purpleEndurer @zsh $. ./a.sh
  1)apple 
  2)banana 
  3)orrange 
  4)peach 
  5)exit
 enter the number before the fruit your liked(1 - 4):3
 You selected orrange
 purpleEndurer @zsh $. ./a.sh
  1)apple 
  2)banana 
  3)orrange 
  4)peach 
  5)exit
 enter the number before the fruit your liked(1 - 4):5
 You selected exit
 purpleEndurer @zsh $. ./a.sh
  1)apple 
  2)banana 
  3)orrange 
  4)peach 
  5)exit
 enter the number before the fruit your liked(1 - 4):0
 Your enter a error number
 purpleEndurer @zsh $. ./a.sh
  1)apple 
  2)banana 
  3)orrange 
  4)peach 
  5)exit
 enter the number before the fruit your liked(1 - 4):9
 Your enter a error number
 purpleEndurer @zsh $

Linux shell编程学习笔记30:打造彩色的选项菜单_学习笔记_02