重击菜单:选择并执行后返回菜单吗? [英] Bash Menu: Return to menu after selection made and executed?

查看:77
本文介绍了重击菜单:选择并执行后返回菜单吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个写入文件的bash脚本.在脚本的末尾,我想显示一个带有行号的菜单-并让用户能够选择1或2(例如,取决于文件中的行数),然后让它执行该行. /p>

到目前为止,这是完美的.

但是,在执行该行之后(例如,它显示了另一个文件.)我想返回菜单,让用户选择另一个数字.包括零以退出菜单.

显示菜单后,我将看到以下内容. (dumpline是读取的文件的行)

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

但是现在-运行变量$ dresult之后-它退出外壳程序(相反,我希望显示菜单.

有什么想法吗?

先谢谢您

解决方案

我认为,您需要类似循环的内容.这是一个用于执行从文件中选择的行的小框架:

#!/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应该足够.
  • 使用子shell可以通过执行文件的一行来防止更改变量.它还可以防止从通常退出shell的行中退出脚本.

I've got a bash script that writes to a file. at the end of the script I want to display a menu, with line numbers - and have the user be able to select 1 or 2, (etc. up to the number of lines in the file) then have it execute that line.

Up to here is perfect.

However, after the line is executed (say for example it displays another file.) I'd like to return to the menu and let the user select another number. Including zero for exiting the menu.

Once the menu is displayed I have the following. (dumpline being the line of the file read)

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

But right now - after running the variable $dresult - it exits the shell (where instead I'd like the menu displayed.

Any thoughts?

thank you in advance.

解决方案

I think, you need something like a loop. Here is a small skelleton for executing a selected line from file:

#!/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

But be aware of the following:

  • Using eval might be not allways be a good idea (escaping is hard). Sometimes $line should be sufficient.
  • Using a subshell prevents changing variables by executing a line of the file. It also does prevent exiting the script from lines that do normally exits a shell.

这篇关于重击菜单:选择并执行后返回菜单吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆