Bash scripting
Redirect to file
# Write hello to file.txt (replacing the whole contents of the file)
echo "hello" > file.txt
# Append hello to the end of file.txt
echo "hello" >> file.txtComments
# this is a single line comment
: '
this
is a
multiline comment'Conditional statements
# define a variable
count=10
# leave spaces before and after brackets
# reference variables with $
# eq, ne, lt, gt, le, ge
if [ $count -eq 10 ]
then
echo "first condition is true"
elif (( $count <= 9 ))
then
echo "second condition is true"
else
echo "all conditions are false"
fi # close if statement
age=10
# and statement - alternatives are
# if [[ "$age" -gt 18 && "$age" -lt 40 ]]
# if [ "$age" -gt 18 -a "$age" -lt 40 ]
if [ "$age" -gt 18 ] && [ "$age" -lt 40 ]
then
echo "Age is correct"
else
echo "Age is not correct"
fi
# or statement - alternatives are
# if [ "$age" -gt 18] || [ "$age" -lt 40 ]
# if [[ "$age" -gt 18 || "$age" -lt 40 ]]
if [ "$age" -gt 18 -o "$age" -lt 40 ]
then
echo "Age is correct"
else
echo "Age is not correct"
fi
# switch statement
car=$1 # read first argument
case $car in
"BMW" )
echo "It's a BMW" ;;
"MERCEDES" )
echo "It's a Mercedes" ;;
"TOYOTA" )
echo "It's a Toyota" ;;
* ) # default case
echo "Unknown car" ;;
esac # close switch statementLoops
Script input
Script output
Compare strings
Numbers and Arithmetic
Arrays
Functions
Files and directories
Debugging
Resources
Articles
Shell Script Best Practices - Shrikant Sharat Kandula
Books
Advanced Bash-Scripting Guide - Mendel Cooper
GitHub repositories
Websites
Amber - The Programming Language compiled to Bash
ShellCheck - shell script analysis tool
Shell Style Guide - Google
Last updated
Was this helpful?