Scripting - Chapter 4: Conditions

From PlayOnLinux
Jump to: navigation, search

Conditions? Can one eat it?

You'd have to be very hungry, but why not? More seriously, a condition will allow you to order your script to do different things according to a test. For example, the value of a variable.

Some examples will make it easier to understand

A test, with no action taken in case of failure:

POL_SetupWindow_menu "What's for dinner?" "Tonight's menu" "Carrots Potatoes French-fries" " "
if [ "$APP_ANSWER" = "Carrots" ]
then
   POL_SetupWindow_message "Let's eat" "Tonight's menu"
fi

The message "let's eat" will only appear if the user chooses Carrots.

A test, with some action in case of failure:

POL_SetupWindow_menu "What's for dinner?" "Tonight's menu" "Carrots Potatoes French-fries" " "
if [ "$APP_ANSWER" = "Carrots" ]
then
   POL_SetupWindow_message "I'm on a hunger strike" "Tonight's menu"
else
   POL_SetupWindow_message "Can I have a second helping?" "Tonight's menu"
fi

The message "I'm on a hunger strike" will only be displayed if the user chooses Carrots. Otherwise the message "Can I have a second helping?" will be displayed.

Threefold test, with no action in case of failure:

POL_SetupWindow_menu "What do you want to eat tonight?" "Tonight's menu" "Carrots Potatoes French-fries" " "
if [ "$APP_ANSWER" = "French-fries" ]
then
    POL_SetupWindow_message "I love french fries" "Tonight's menu"
elif [ "$APP_ANSWER" = "Potatoes" ]
then
    POL_SetupWindow_message "I agree to eat potatoes tonight" "Tonight's menu"
elif [ "$APP_ANSWER" = "Carottes" ]
then
    POL_SetupWindow_message "I do not like carrots" "Tonight's menu"
fi

What this code does should be clear enough after seeing the previous examples.

In Bash, you can use either single-quotes ('), aka apostrophe, or double-quotes ("), aka quote. We highly recommend, as a standard, to use double-quotes ("), aka quote, so that you can use apostrophe in your string, if needed. Though, it is also preferred not to use contractions (which require an apostrophe, or single-quote (')) at all to avoid this situation altogether. The choice is yours; choose whichever is the cleanest, easiest-to-read, most-concise code.

Previous: Chapter 3: Variables

Next: Chapter 5: Wine