How to get result of selection of menu gdialog in variable in Shell Script?

5

I'm creating a simple script for learning in which the user should:

  • Type number to be saved in variable NUM1
  • Enter a second number that will be saved in variable NUM2
  • Choose from the menu if it wants to add, subtract, multiply or divide these numbers.

After these procedures, it should appear in the terminal "The option chosen was: sum (such as if it had chosen subtraction, subtraction would appear there [without accent because it is the variable that I want to appear]

Code I created:

#!/bin/bash

clear

NUM1=$( gdialog --inputbox "Informe o número 1"
gdialog --title 'Aviso' )

NUM2=$( gdialog --inputbox "Informe o número 2"
gdialog --title 'Aviso')

escolha=$( gdialog \
           --menu 'Escolha:' \
           0 0 0 \
           soma '+' \
           subtracao '-' \
           multiplicacao '*' \
           divisao '/' )

echo "A opção escolhida foi: $escolha"

exit

Problem: When I run, I do all the procedures as user until the choice in the menu, appears in the terminal what was chosen, however, is not what I asked to appear and immediately below "The option chosen was:" and does not appear variable on the front.

I would like this variable to appear to see that it is actually being saved in $ choice, so I can find a way to use the switch case and finish my script.

NOTE: I use gdialog for visual mode.

    
asked by anonymous 09.03.2017 / 17:56

2 answers

1

Short answer: gdialog sends the output to and STDERR; so you need to redirect STDERR to STOUT or to join 2>&1 to invocations of gdialog :

escolha=$(gdialog .......... 2>&1) 

Eventually lurks zenity

num1=$(zenity --title "Aviso" --entry --text "numero 1")

As a slightly different philosophy, I suggest the gtkdialog

#! /bin/bash

export MAIN_DIALOG='
 <vbox>
  <hbox>
    <entry> <variable>E1</variable> </entry>
    <entry> <variable>E2</variable> </entry>
  </hbox>
  <hbox>
    <button> <label>+</label> <action> echo $(($E1+$E2))</action> </button>
    <button> <label>-</label> <action> echo $(($E1-$E2))</action> </button>
    <button> <label>*</label> <action> echo $(($E1*$E2))</action> </button>
    <button> <label>/</label> <action> echo $(($E1/$E2))</action> </button>
    <button ok></button>
  </hbox>
 </vbox>'

gtkdialog --program=MAIN_DIALOG
    
18.03.2017 / 17:47
4

I took the liberty of changing your script to a more simplified and readable way, thus:

#!/bin/bash

operacao=""

echo "Digite o primeiro valor"
read valor1
sleep 3
echo ""
echo "Digite o segundo valor"
read valor 2
sleep 3
echo ""
echo "Escolha a operação: "
echo "1 - soma"
echo "2 - Subtração"
echo "3 - Multiplicação"
echo "4 - Divisão"
read operacao
case $operacao in
    1) operacao="Soma" ;;
    2) operacao="Subtração" ;;
    3) operacao="Multiplicação" ;;
    4) operacao="Divisão" ;;
    *) echo "Opção inválida" ; exit ;;
esac

echo "A opção foi: $operacao"
    
09.03.2017 / 18:18