Bash Menu: return to the menu after the selection made and executed?

I have a bash script that is being written to a file. at the end of the script, I want to display a menu with line numbers - and the user will be able to select 1 or 2 (etc. up to the number of lines in the file), then execute this line.

Perfect before that.

However, after the line is executed (say, for example, it displays a different file.) I would like to return to the menu and let the user select a different number. Including zero to exit the menu.

After displaying the menu, I have the following. (dumpline - line of the read file)

     dresult=`sed -n "$dumpline"p "$PWD"/"$myday1"_"$myjob".txt`
     $dresult

But right now - after running the $ dresult variable - it leaves the shell (instead, I want the menu to display.

Any thoughts?

thank you in advance.

0
3

, - . skelleton :

#!/bin/bash

dumpfile="bla.txt"

echo "ls
echo 'hello'" > ${dumpfile}

function do_action {
    line="$( sed -n "${1},1p" "$dumpfile" )"
    (
        eval "${line}"
    )
}

cat -n $dumpfile
nr=$( cat "${dumpfile}" | wc -l )
PS3="select line nr or nr for QUIT: "
select ACTION in $( seq "$nr" ) QUIT
do
    case $ACTION in
        QUIT) echo "exit" ; break ;; #EXIT
        *) do_action "$ACTION" ;;
    esac
done

:

  • eval ( ). $line .
  • . script , .
0

, cat, ( cat - . , ). :

while [[ 1 ]]
do
    cat -n menufile
    read -p "Make a selection " choice
    case $choice in 
        1|2) 
           echo "A or B"
           ;;
        3) 
           echo "C"
           ;;
        4) 
           break
           ;;
        *) 
           echo "Invalid choice"
           ;;
    esac
done

cat -n:

saveIFS="$IFS"
IFS=$'\n'
read -d '' -a menuarray < menufile
IFS="$saveIFS"

for (( i=0; i<${#menuarray[@]}; i++ ))
do
    menu=$menu"$(($i+1))) ${menuarray[i]}"$'\n'
done

while [[ 1 ]]
do
    echo "$menu"
    read -p "Make a selection " choice
    case $choice in 
        1|2) 
           echo "A or B"
           ;;
        3) 
           echo "C"
           ;;
        4) 
           break
           ;;
        *) 
           echo "Invalid choice"
           ;;
    esac
done
+2

My comments in the dz answer are too long for the comment, so I post them here:

Using seqwith selectwill make the menu look redundant, without correlation between it and the display of lines in $dumpfile:

ls
echo 'hello'

1) 1
2) 2
etc.

Instead, you can do something like this:

saveIFS=$IFS
IFS=$'\n'
menu=$(< $dumpfile)
PS3="Make a selection: "
select ACTION in $menu QUIT
do
    IFS=$saveIFS
    case ...
+1
source

Source: https://habr.com/ru/post/1722539/


All Articles