I am stuck with a little problem in bash. what I want to do is: when booting my raspberry pi to login automatically and startup a script where I can choose (menu like, I use dialog) which program to start. but, when not choosing an option for 10 seconds a default action (the first option) shall be executed.
well, the first part works. but I am not able to include a timer or timeout. the timeout-option itself simply terminates the script after 10 seconds, but does not run any program.
here is what I have so far (the echo is for testing purpose):
#!/bin/sh
sw=`dialog --menu "choose a program" 20 73 8 "1) program 1" "this will start program 1" "2) program 2" "this will start program 2" 3>&1 1>&2 2>&3`
case "$sw" in
"1) program 1")
echo "program 1 is running" ;;
"2) program 2")
echo "program 2 is running" ;;
esac
I know, it is not much. mainly, because all my attempts led to a dead-end (for my understanding - I tried to build while- and for-loops with a sleep command around it).
Unfortunately searching the web did not help (again: for my understanding), so do you guys have an idea (or a solution) how to fix this issue? I just started learning bash.
You need to look at the exit code when dialog exits. (That will be the value of $?
but you need to grab it right away because it is reset after every command.)
You probably also want to customize the return codes, which you can do by defining some environment variables. In the following snippet, I set DIALOG_ERROR
to 5, which will apply to the timeout (and other random errors), while I set DIALOG_ESC
to 1 so that it will be the same as choosing the Cancel button. By default, ESC and timeout effectively return the same value (255, even though the manpage says -1, because process exit codes are only eight bits and are conventionally unsigned). If you want the Escape key to quickly select the default, then you could set DIALOG_ESC
to 5 as well.
sw=`DIALOG_ERROR=5 DIALOG_ESC=1 dialog --timeout 10 \
--menu "choose a program" 20 73 8 \
"1) program 1" "this will start program 1" \
"2) program 2" "this will start program 2" \
3>&1 1>&2 2>&3`
rc=$?
case $rc in
0) case "$sw" in
"1) program 1")
echo "program 1 is running" ;;
"2) program 2")
echo "program 2 is running" ;;
esac;;
1) echo You hit Cancel, doing nothing;;
5) echo Running default program;;
*) echo Unhandled exit code $rc;;;
esac
The other exit codes, none of which are applicable to this example:
See man dialog
for details (search for DIAGNOSTICS
. It's near the end.)