0

I want to call the unix dialog editbox from within a generic function in bash. The two outcomes I am interested in are:

  1. If the user hits OK I would like to capture what the user has entered into the editbox
  2. Detect if the user hits Cancel

Here is some code I have but I'm not sure if this is the best way:

function ib_generic()
{
    tmp_file="/tmp/file.tmp"
    if [ -f $tmp_file ]
    then
    rm -f $tmp_file
    fi
    
    mkfifo $tmp_file

    # push the user input to $tmp_file
    dialog --stdout \
    --title "$1" \
    --backtitle  "My Backtitle" \
    --inputbox "$2" 20 40 2> $tmp_file &

    # detect 'cancel' or 'escape':
    if [[ $? -eq 0 || $? -eq 255 ]] 
    then
        rm -f $tmp_file
        echo 1
    else # 'ok' was pressed so proceed:
        result="$( cat /tmp/file.tmp )"
        rm -f $tmp_file
        echo $result
    fi
}

What's the best way to cancel the result if OK is hit and if not, how to detect Cancel or Escape?

Pat Mustard
  • 1,852
  • 9
  • 31
  • 58

2 Answers2

1

Don't run dialog in the background, since it won't wait for it to finish and won't set $?.

You also have the exit statuses wrong. 0 means OK was pressed, 1 means Cancel, and 255 means Escape.

dialog --stdout \
    --title "$1" \
    --backtitle  "My Backtitle" \
    --inputbox "$2" 20 40 2> "$tmp_file"

exit=$?
if [ $exit -eq 0 ] # OK was pressed
then
    echo "$result"
elif [ $exit -eq 1 ] || [ $exit -eq 255 ] # Cancel or Escape was pressed
then
    echo 1
else
    echo 2
fi

There's a fuller example here

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

Dialog returns different exit codes on each button, here's how i'd do it:

input=$(
    dialog --stdout \
           --title "test" \
           --backtitle  "My Backtitle" \
           --inputbox "$2" 20 40 
)

case $? in
     0) echo "ok $input";;
     1) echo 'cancel'   ;;
     2) echo 'help'     ;;
     3) echo 'extra'    ;;
   255) echo 'esc'      ;;
esac

More info is here

Ivan
  • 6,188
  • 1
  • 16
  • 23