我可以更改选择选项的显示方式吗?


8

我正在使用bash中的select和case。我目前有9个选项,可以很好地整理整齐的3x3网格选项,但显示如下:

    1) show all elements  4) write to file      7) clear elements
    2) add elements       5) generate lines     8) choose file
    3) load file          6) clear file         9) exit

我希望它显示在列之前的行中:

1) show all elements  2) add elements    3) load file
4) write to file      5) generate lines  6) clear file  
7) clear elements     8) choose file     9) exit

有什么办法可以做到这一点?最好是在脚本中易于设置和取消设置的东西,例如shell选项。如果重要的话,这些选项将存储在数组中,并在case块中由数组的索引引用。

OPTIONS=("show all elements" "add elements" "load file" "write to file" "generate lines" "clear file" "clear elements" "choose file" "exit")

...

select opt in "${OPTIONS[@]}"
do
case $opt in
    "${OPTIONS[0]}")

...

    "${OPTIONS[8]}")
        echo "Bye bye!"
        exit 0
        break
        ;;

    *)
        echo "Please enter a valid option."
esac
done

Answers:


7

创建自己的“选择”:

#!/bin/bash

options=("show all elements" "add elements" "load file" "write to file" "generate lines" "clear file" "clear elements" "choose file" "exit")
width=25
cols=3

for ((i=0;i<${#options[@]};i++)); do 
  string="$(($i+1))) ${options[$i]}"
  printf "%s" "$string"
  printf "%$(($width-${#string}))s" " "
  [[ $(((i+1)%$cols)) -eq 0 ]] && echo
done

while true; do
  echo
  read -p '#? ' opt
  case $opt in
    1)
      echo "${options[$opt-1]}"
      ;;

    2)
      echo "${options[$opt-1]}"
      ;;

    9)
      echo "Bye bye!"
      break
      ;;
  esac
done

输出:

1)显示所有元素2)添加元素3)加载文件             
4)写入文件5)生成行6)清除文件            
7)清除元素8)选择文件9)退出                  
#? 
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.