Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux script select menu

Tags:

shell

select

I need to create a select menu with six options using the select loop and the case instruction BUT NOT THE ECHO COMMAND FOR THE MENU OPTION and they have to display like this:

1) opt1
2) opt2
3) opt3
4) opt4
5) opt5
6) opt6

And not like:

1) opt1 3) opt3 5) opt5
2) opt2 4) opt4 6) opt6

So far I have this code, but the problem is with the display, with 5 options it displays vertically, but with 6 it displays side by side:

#! /bin/sh
PS3="Enter your choice :"
select choice in "opt1" "opt2" "opt3" "opt4" "opt5" "Exit"; do
case $REPLY in
    1) echo "$choice";;
    2) echo "$choice";;
    3) echo "$choice";;
    4) echo "$choice";;
    5) echo "$choice";;
    6) echo "see you next time";break;;
    *) echo "Wrong choice!";;
esac
done
like image 734
user2420374 Avatar asked Aug 25 '26 10:08

user2420374


1 Answers

Adjusting the COLUMNS variable helps to limit the number of columns in the menu. I typically do (in a script):

COLUMNS=1
select ...

when I want one column all the time.

To be precise, COLUMNS=1 means that your TERMINAL is ONE CHARACTER wide. The select command then has no choice but to then print ONE COLUMN of menu items.

To be REALLY accurate, you could

  1. find the length of the longest item (itemLen)

THIS IS INCORRECT=> 2. find the number of items and mod by ten to get the max number of digits (numberLen) <=

  1. find the total number of items "n" and calculate int(log10(n))+1 (numberLen)
  2. COLUMNS=((itemLen + numberLen = 2))

where the '2' is for the paren and space between the menu item number and the item. But this is not necessary.

like image 132
mpersico Avatar answered Aug 27 '26 05:08

mpersico



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!