Shell Conditional Processing

Examples

Run a command only if previous command succeeds

command1 && command2

NOTE: Using a single ampersand runs one command after another without error checking

You can also achieve this using an if statement...

if command1

then

   command2

fi

Run a command only if previous command fails

command1 || command2

You can also achieve this using an if statement...

if ! command1

then

   command2

fi

Run a different command on success or failure

if command1

then

   command2

else

   command3

fi

Run a command based on user entry

A menu to add the correct keys to your keychain and ssh to a chosen target server...

Shows example usage of select and case

   # Show menu

   # =========


   COLUMNS=20

   echo "Main Menu"

   echo "---------"

   select choice in "Exit" \

                    "MYSERVER1" \

                    "MYSERVER2" \

                    "MYSERVER3" \

                    "MYSERVER4"

   do

      case ${REPLY} in

         1)   exit 0 ;;

         2)   ssh myuser@myserver1

              exit 0;;

         3)   ssh myuser@myserver2

              exit 0 ;;

         4)   ssh myuser@myserver3

              exit 0 ;;

         5)    ssh myuser@myserver4

              exit 0 ;;

      esac

   done

Tip: Save the script in ~/bin and use an alias to make it available by typing menu when you log in.

Using COLUMNS=20 makes the menu items appear in a single vertical list instead of multiple columns.