How to use lines as a selectable function in shell script?

195 views Asked by At

I'm currently creating a script to retrieve a set of lines from a file and will let users select any one of them to perform certain task.

Eg:

echo "my_files"
1) my_files1
2) my_files2
3) my_files3
...
n) my_filesN

I want to let the user select any one of these line and perform certain task based on the selection in shell script.

2

There are 2 answers

2
Barmar On

Read the filenames into an array with readarray.

Use the select built-in to display the list of files as a menu.

echo "Select a file":
readarray -t files list_of_files.txt
select file in "${files[@]}"; do
    echo "You selected $file";
done
0
Walter A On

Perhaps you want to have something like the next menu:

#!/bin/bash

test -f "$1" || { echo "File \"$1\" can not be found."; exit 1; }

readarray -t options < "${1}"

# set the prompt used by select, replacing "#?"
PS3="Use a number to select a command or 'q' to cancel: "

stopmenu=
while [[ -z "${stopmenu}" ]]; do
   select opt in "${options[@]}" ; do
      if [[ ${REPLY} = q ]]; then
         stopmenu=1
    break
      fi
      if [[ ${#opt} -gt 0 ]]; then
         echo "$opt"
         source <(echo "${opt}")
      fi
      break
   done
   echo
done

You can give a filename with shell commands as an argument, something like menu myfile. The file with menu options can look like

echo "Hello world"
echo "Comment is allowed" # Just add text after a hash.
ls -l
echo "Value of xxx=[${xxx}]" # xxx can be filled in the next menu option
read -p "Enter value for xxx: " xxx # The variable xxx will be known in the menu