0

How can i define a shortcut like "c" for "create", "d" for "delete" or "n" for "new" by select menus in shell scripts?

Code:

#!/bin/bash

PS3="Enter an option: "

select option in create delete new quit
do
    echo "Selected option was: $option"

if [ "$option" == "create" ]

then
 
read -r -p 'Create new partition: Please define a name of the partition: ' new_partition

read -r -p 'Define Size: Please define a size of the partition: ' partition_size

break

fi

if [ "$option" == "delete" ]

then
 
read -r -p 'Delete partition: Please define a name of the partition: ' delete_partition

break

fi

if [ "$option" == "new" ]

then
 
read -r -p 'Reset memory usage: Please define a name of the partition: ' reset_partition

break

fi

if [ "$option" == "quit" ]

then

break

fi

done

2
  • 2
    1. learn to indent your code so that it's readable. 2. install and use shellcheck (or paste your code into shellcheck.net) - your code will not run as is, due to multiple instances where there is a missing space after [ and before ]. 3. you should also double-quote your variables, including $option.
    – cas
    Jun 10 at 9:57
  • I have edited it.
    – Coder_74ZB
    Jun 10 at 10:06

2 Answers 2

0

Whatever you enter to the select prompt will be reflected in the $REPLY variable. Unfortunately you have to hit the "enter" key to terminate the input. So $REPLY will hold the "c", "d", "n", or "q" character, whenever either was entered, and you can run a case statement on it:

PS3="enter create, delete, new, quit, and hit <Return> "
select OP in create delete new quit
  do echo ">$OP<, >$REPLY<"
  done
1) create
2) delete
3) new
4) quit
enter create, delete, new, quit, and hit <Return> c
><, >c<
enter create, delete, new, quit, and hit <Return> d
><, >d<
enter create, delete, new, quit, and hit <Return> 1
>create<, >1<
enter create, delete, new, quit, and hit <Return> 
3
  • My idea was if you enter a character "c" then the program jumps to "create" and so on.
    – Coder_74ZB
    Jun 10 at 10:36
  • Then, I'm afraid, you can't use select. Try read -n1 instead.
    – RudiC
    Jun 10 at 18:40
  • maybe use iselect instead. it's not a built-in like select is, but it is "ncurses-enhanced" and does have some extra features that select doesn't.
    – cas
    Jun 11 at 10:09
0

Read input and then case switch:

#!/bin/sh

echo select... c: create, d: delete, x:xxx...

read OPT

case $OPT in
c*)
echo c
;;

d*)
echo d
;;

*)
echo “User Selected Choice not present”
exit 1

esac

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.