Introduction to Bash Scripting

Bash (Bourne Again Shell) is a command-line shell/programming language by the GNU Project. It is the default shell for most Unix-based systems, including Linux and macOS. Bash scripting allows you to automate tasks on these systems, making it a powerful tool for developers and system administrators.

A Bash script is a text file containing a series of commands that are executed sequentially. These scripts can incorporate programming constructs such as variables, functions, loops, and conditional statements, allowing for complex automation workflows.

Whether you’re automating system tasks, orchestrating server processes, or just creating helpful tools, Bash scripting is an essential skill for anyone working with Unix-based systems.

This cheat sheet provides a quick reference to key features and syntax of Bash scripting to help you create your scripts more efficiently.

Starting a Bash Script

bash
#!/bin/bash
# This is a comment

Variables

bash
VARIABLE="Hello World" # Define a variable
echo $VARIABLE # Use a variable

String

bash
STRING="Hello, World!"
echo ${#STRING} # Length of string
SUBSTRING=${STRING:0:5} # Substring

Arrays

bash
ARRAY=("Apple" "Banana" "Cherry") # Define an array
echo ${ARRAY[0]} # Access an array element
ARRAY[0]="Apricot" # Modify an array element
echo ${ARRAY[@]} # All items in an array
echo ${#ARRAY[@]} # Number of items in an array

If Statement

bash
if [ $VAR -gt 10 ]
then
echo "Greater than 10."
elif [ $VAR -eq 10 ]
then
echo "Equal to 10."
else
echo "Less than 10."
fi

For Loop

bash
for i in {1..5}
do
echo "Welcome $i times"
done

While Loop

bash
COUNTER=0
while [ $COUNTER -lt 10 ]
do
echo "The counter is $COUNTER"
let COUNTER=COUNTER+1
done

Case Statement

bash
case $VAR in
"option1")
echo "Option 1"
;;
"option2")
echo "Option 2"
;;
*)
echo "Other"
;;
esac

Functions

bash
function hello() {
echo "Hello, World!"
}
hello # Call the function

Reading User Input

bash
echo "What's your name?"
read USER_NAME
echo "Hello, $USER_NAME!"

File Operations

bash
cat file.txt # Print file content
less file.txt # View file content with paging
cp source.txt dest.txt # Copy file
mv source.txt dest.txt # Move file
rm file.txt # Delete file
touch file.txt # Create new file

Directory Operations

bash
ls # List directory contents
cd /path/to/directory # Change directory
mkdir directory # Make new directory
rmdir directory # Remove directory

Pipes and Redirection

bash
command1 | command2 # Pipe, send output of command1 as input to command2
command > file # Redirect standard output to a file
command >> file # Append standard output to a file
command < file # Redirect standard input from a file
command 2> file # Redirect standard error to a file
command1 2>&1 | command2 # Pipe both standard output and standard error to command2

Command Exit Status

bash
command
echo $? # Show exit status of the last command

Tips & Advice

  • Always use double quotes around variables to avoid any word splitting or globbing issues.
  • Use set -e at the start of your script to make the script exit if any command within it fails.
  • Use set -u to prevent usage of undefined variables.
  • If a script is meant to be sourced (i.e., run in the current shell rather than a subshell), then use return instead of exit to stop the script on error.
  • When reading user input, you can use the -p option with the read command to provide a prompt. For example, read -p "Enter your name: " name will display the prompt “Enter your name: ” and store the user’s input in the name variable.
bash
read -p "Enter your name: " name
echo "Hello, $name!"

Remember, practice is key when it comes to mastering any programming language, including Bash scripting. Use this cheat sheet as a reference and keep practicing!