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 variableecho $VARIABLE # Use a variable
String
bash
STRING="Hello, World!"echo ${#STRING} # Length of stringSUBSTRING=${STRING:0:5} # Substring
Arrays
bash
ARRAY=("Apple" "Banana" "Cherry") # Define an arrayecho ${ARRAY[0]} # Access an array elementARRAY[0]="Apricot" # Modify an array elementecho ${ARRAY[@]} # All items in an arrayecho ${#ARRAY[@]} # Number of items in an array
If Statement
bash
if [ $VAR -gt 10 ]thenecho "Greater than 10."elif [ $VAR -eq 10 ]thenecho "Equal to 10."elseecho "Less than 10."fi
For Loop
bash
for i in {1..5}doecho "Welcome $i times"done
While Loop
bash
COUNTER=0while [ $COUNTER -lt 10 ]doecho "The counter is $COUNTER"let COUNTER=COUNTER+1done
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_NAMEecho "Hello, $USER_NAME!"
File Operations
bash
cat file.txt # Print file contentless file.txt # View file content with pagingcp source.txt dest.txt # Copy filemv source.txt dest.txt # Move filerm file.txt # Delete filetouch file.txt # Create new file
Directory Operations
bash
ls # List directory contentscd /path/to/directory # Change directorymkdir directory # Make new directoryrmdir directory # Remove directory
Pipes and Redirection
bash
command1 | command2 # Pipe, send output of command1 as input to command2command > file # Redirect standard output to a filecommand >> file # Append standard output to a filecommand < file # Redirect standard input from a filecommand 2> file # Redirect standard error to a filecommand1 2>&1 | command2 # Pipe both standard output and standard error to command2
Command Exit Status
bash
commandecho $? # 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 ofexit
to stop the script on error. - When reading user input, you can use the
-p
option with theread
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 thename
variable.
bash
read -p "Enter your name: " nameecho "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!