Help with scripting

Hi,

I’d like to make a script using the alert, so I can make some responses according to the button chosen by the user. If I understand well, the alert can get a maximum of 3 buttons.
I’ve found how to script with 2 buttons, but I can’t get the result from the 3rd one.

For example:

alert --info "One or Two or Three" One Two Three
if [ $? = 0 ]; then 
    echo "one chosen"
elif [ $? = 1 ]; then
	echo "two chosen"
elif [ $? = 2 ]; then
	echo "three chosen"
else
    echo "can't be chosen"
fi

If I push the 3rd button, I’ll get this in the console:

Three
two chosen

What am I doing wrong?

That’s because you’re overwriting $? with the result of the first test : [ is a command, it’s actually an alias for test, which also returns an error code.
Alert sets $? to 2.
So the first test is false ($? is not 0), so test returns 1.
The second test is true, since $? is now 1.

You want to cache the return value and test the cache variable instead:

alert --info "One or Two or Three" One Two Three
b=$?
if [ $b = 0 ]; then 
    echo "one chosen"
elif [ $b = 1 ]; then
	echo "two chosen"
elif [ $b = 2 ]; then
	echo "three chosen"
else
    echo "can't be chosen"
fi
3 Likes

thanks a lot, it’s working perfectly now!