Reputation: 4108
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?
Upvotes: 0
Views: 1500
Reputation: 3519
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
Upvotes: 1