Bash scripting & cheatsheet
I’ll present you with a curated list of the most handy things to know for Bash scripting. These are some of the most useful components, but they aren’t easy to remember for everyone. Next time your mind is blanking when writing a Bash script, take a look at the Bash scripting cheat sheet below for some quick help.
Bash Scripting Basics:
Here are some of the most basic things to know about Bash scripting. If you are not sure where to start, this would be a good choice.
Conditional statements
Conditional statements with if
or case
allow for us to check if a certain condition is true or not. Depending on the answer, the script can proceed different ways.
For case
statements it is best to just see a basic example:
For case
statements it is best to just see a basic example:
#!/bin/bash
day=$(date +"%a")case $day in Mon | Tue | Wed | Thu | Fri)
echo "today is a weekday"
;; Sat | Sun)
echo "today is the weekend"
;; *)
echo "date not recognized"
;;
esac
Basic if
example script:
#!/bin/bash
if [ $1 -eq $2 ]; then
echo "they are equal"
else
echo "they are NOT equal"
fi
Bash Loops
Bash loops allow the script to continue executing a set of instructions as long as a condition continues to evaluate to true.
Read User Input
Prompt the user for information to enter by using read
command:
#!/bin/bash
read -p "What is your name? " nameecho "Enjoy this tutorial, $name"
Parse input given as arguments to the Bash script:
#!/bin/bash
if [ $# -ne 2 ]; then
echo "wrong number of arguments entered. please enter two."
exit 1
fiecho You have entered $1 and $2.