0

I'm working on a simple bash script menu, and I've followed this guide to get started.

It works fine, but I don't really like how stderr is redirected to a file and then used in the main loop.

In my script I have a few functions that draw different things. I'm trying to modify them to work without having to write to the files. One of the functions to draw a menu looks like th is (simplified):

function render_menu()
{
    dialog --clear --backtitle "$backtitle" --title "Some Title" --menu "My  fancy menu" 50 15 4 "one" "option 1" "two" "option 2"
    echo $?
}

And it is called from the main loop like:

while true; do
    selection="$(render_menu)" 

    case $selection in
            Quit) break;;
            Back) #some logic;;
            *) #some logic;;
    esac
done

But it doesn't work, when I run the script I don't see the menu. I assume because the output of dialog has been redirected?

The way I want it to work is that the dialog is displayed, and the output from it is stored in the variable selection. Is that possible without the need for an external file? If not, why so?

1
  • All the output of a command that is assigned to a variable is put inside that variable. Selection will contain the return code and the entire contents of dialog. Commented May 27, 2015 at 9:47

1 Answer 1

1

Try as:

#!/bin/bash
#

function render_menu()
{
  exec 3>&1
  selection=$(dialog --clear --backtitle "$backtitle" --title "Some Title" --menu "My  fancy menu" 50 15 4 "one" "option 1" "two" "option 2" 2>&1 1>&3)
  exit_code=$?
  exec 3>&-
}

render_menu 
echo $exit_code
echo $selection

*** Addendum 1 ***

If, for some reason, the function must be called as $(render_menu ...) and return result in stdout, this is another possibility:

#!/bin/bash 
#

function render_menu()
{
   selection=$(dialog --clear --backtitle "$backtitle" --title "Some Title" --menu "My  fancy menu" 50 15 4 "one" "option 1" "two" "option 2" 2>&1 1>&3)
  exit_code=$?
   echo $selection
}

exec 3>&1
selection="$(render_menu  2>&1 1>&3)"
exec 3>&-
echo $selection
Sign up to request clarification or add additional context in comments.

2 Comments

That's not really how I would like it. I prefer to write my scripts so that the functions echo a value back, and then I just use command expansion to put it in a variable. Perhaps I should have been more clear in the question that I want to leave the loop as-is and modify the render menu function only
These are minor variants over same answer. Updated, feel free of provide your own variants.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.