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 checkingYou 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
Run a command based on a test result
if [ $(whoami) = root ]
then
echo "root"
else
echo "Error: not root"
fi
Bibliography
casehttps://linuxize.com/post/bash-case-statement/
ifhttps://stackoverflow.com/questions/7402587/run-command2-only-if-command1-succeeded-in-cmd-windows-shellhttps://ryanstutorials.net/bash-scripting-tutorial/bash-if-statements.php
testhttps://linuxhint.com/bash-test-command/