Bash Scripting Cheat Sheet [Free PDF Download]

Bash (Bourne Again SHell) is a powerful and widely used language. It provides plenty of features and tools to automate tasks, manage files, process data and much more. However, remembering all the syntax and commands can be challenging. This Bash scripting cheat sheet serves as a quick reference of essential concepts, syntax and basic structure of the language. It covers a range of topics, including variables, conditionals, loops, functions and string operations of Bash scripting. Each section provides clear explanations and practical examples to help you understand the concepts and structure of the language.

Download Bash Scripting Cheat Sheet

Bash scripting cheat sheet image

Available Download Options


Most Popular

PDF (4 Pages)

DOC (4 Pages)

Combo Pack

ZIP (pdf, docx, png)

Syntax of Bash Script

The syntax of a programming language defines the set of rules and conventions that govern how programs are written. Every programming language has its own syntax and structure. Bash scripting syntax is straightforward and easy to grasp. For writing a correct and functional script one must have a clear understanding of the Statement, Variables, Data types, Control Structure etc.

Basic Syntax

If you are a complete beginner and never write any script on Bash this is where you can start from. This section covers the basic syntax of Bash scripting including Shebang and exit way in Bash scripting.

Syntax Description
#! /bin/bash Shebang at the beginning of a script specifies the interpreter
#! /usr/bin/env bash Alternative shebang -using environment variable
$# Stores the number of argument passes to the Bash script
$1 , $2, $3 Variables that store the values passed as arguments to the Bash script
exit Exit from the Bash script
CTRL + C Keyboard shortcut to stop Bash
$ (command_name) Execute a command inside a subshell
sleep Pause for a specified number of seconds, minutes, hours or days

Comments

Comments are important for writing clean, concise and easily understandable code. It offers a coder to write complex code in a human-understandable form. In Bash script, the coder can explain the intent or purpose of the code in a single or multi-line comment using the following easy syntax.

Syntax Description
# Single line comment. The text comes after it will not be executed
: <<‘ ‘ Multiple line comment

Single and multiple line of comments in Bash scripting:

echo "Explain the code in a single line comment:"  
# This is a single line comment.
: '
This is a multiline comment
Next line of the comment
Following line of the comment
'

Variables

Variables are an essential part of any programming language. Bash script variables allow to store, manipulate and retrieve data dynamically. This section is going to investigate the structure of variables, accessing the value of the variable in Bash script and other basics related to variables.

Syntax Description
var_name=val Assign a value to the specified variable
$ var_name Access the value of the specified variable
“$var_name” Variables with special bash script character at the beginning must be quoted with double quotes or single quotes
var_name=$(command) Assign the output of a command to the specified variable
readonly var_name=val Prevent the value of a specified variable to be modified
$HOME, $PATH, $USER etc. Few predefined environment variables
$0 Predefined variable that stores the name of the script
$# Predefined variable that stores the number of command line arguments
#? Predefined variable that stores the exit status of the last executed command
$$ Predefined variable that stores the process ID of the current script
$! Predefined variable that stores the process ID of the last background command
unset var_name Delete a variable with specified name

Different types of variables and variable properties:

name="John"

echo $name     # Output: John

"$age"=25

echo $("$age")     # Output: 25

current_date=$(date)     # assign the output of date command to current_date

readonly profession="IT specialist"     # This variable can't be modified

unset name     # Output: Delete the variable called name

Command Execution

Command execution is a fundamental concept that allows Bash programmer to run commands and programs within a script. Here is a quick demonstration of Bash script command syntax, command substitution, directing standard input and standard output of commands and other commands execution techniques.

Syntax Description
command_name Directly execute the command with specified name
`variable_name=command` Older version of substituting the output of the command to a specified variable
command > file_name Redirect the output of a command to a specified file
command >> file_name Redirect the output of a command to a specified file and append it with the existing content
command1 | command2 Use the standard output of command1 as the standard input of command2

Command execution, command substitution and redirecting output in Bash:

ncal     # execute the ncal command and display its return value

`content_list=ls`     # execute the ls command and stores its return value in content_list variable

ls > files_list.txt     # execute the ls command and stores its return value in files_list

date >> files_list.txt     # execute the date command and appends its return value in files_list

date | echo     # execute the date command pass its output as the input of echo command

Input/Output

Bash scripts can prompt users for input during runtime. Moreover, it can read input data from files and can redirect the output to a file. This allows the user to process data from external sources or generate output files containing the results of the script’s execution.

Syntax Description
read -p Prompt the user for information to enter
command < input_file Redirect input from a file to a command
command 2> error_file Redirect standard error to a specified file
command &> file_name Redirect standard output and standard error to a specified file

Examples of taking input and prompting output in Bash code:

echo "What is your name?"

read name     # Promt the user to input his/her name and stores the input value in name variable

echo "Hello, $name!"
wc -l < input_file.txt     # Redirect input from input_file.txt to wc -l

wc -l 2> error_file.txt     # Redirect error of wc -l command to error_file.txt

wc -l &> log.txt     # Redirect standard output or error of wc -l command to log.txt

Data Types

Bash script offers few data types to handle a different kind of information within scripts. The data types of Bash language are mainly String, Numeric and Array.

Syntax Description
x=5 Integers are treated as Number
is_valid=0 Boolean value represents False
is_valid=1 Boolean value represents True
declare -a var=value Declare an indexed array
declare -A var Declare an associated array
declare -i var=value Declare an integer variable
declare -r var=value Declare a read-only variable
declare -x var=value Declare an exported variable
var_name=”” Absence of value or an uninitialized variable
array=(“element1” “element2” “element3″…) A collection of elements accessed using numerical indices
declare -A array1

array1[“element1″]=”value1”

array2[“element2″]=”value2”

 A collection of elements accessed using string indices
var=”Hellow World” Sequence of characters enclosed in single or double quotes is treated as String

Various data types in Bash programming language:

name="John"             # String variable

count=10             # Numeric value

fruits=("apple" "banana" "orange")      # Index Array
declare -A ages                         # Declare an associative array

ages["John"]=25                         # Assigning value to a key

ages["Andrew"]=35                      # Assigning value to another key

Conditional Statements

Conditional statement in Bash scripting allows us to control the flow of the program based on certain condition. There are three basic types of conditional statements in Bash scripting. These are if, elif and case statements. These statements evaluate conditions and execute different sets of code or commands depending on whether the conditions are true or false.

Syntax Description
if [ condition ]; then
#code
fi
Test a condition and execute the then clause if it is true
if [ condition ]; then
#code
fi
else
#code
fi
Execute the then clause if the condition is true, otherwise execute the else clause
if [ condition1 ]; then
#code
elif [ condition2 ]; then
#code
else
#code
fi
Execute the then clause if the condition is true or execute the elif clause if  the condition is true, otherwise execute the else clause
case variable in
pattern1)
#code
;;
pattern2)
#code
;;
pattern3)
#code
;;
*)
;;
esac
Execute code following each pattern if the variable matches the pattern otherwise, execute * if none of the patterns match
test condition Returns 0 or 1 indicating whether the condition is true or false
Structure of conditional statements in Bash scripting:

age=18
if [ "$age" -ge 18 ]; then
  echo "You are an adult."
fi
age=16
if [ "$age" -ge 18 ]; then
 echo "You are an adult."
else
 echo "You are not an adult."
fi
score=85
if [ "$score" -ge 90 ]; then
 echo "You achieve Grade: A" 
elif [ "$score" -ge 80 ]; then
 echo "You achieve Grade: B"
else
 echo "You achieve Grade: C" 
fi
fruit="apple"
case $fruit in "apple")
 echo "It's an apple." 
 ;;
"banana" | "orange")
 echo "It's a banana or an orange."
 ;;
 *)
 echo "The fruit name is not in the list."
 ;;
esac

Loops

Loops are an essential feature of any programming language. They provide a way to automate repetitive tasks, iterate over data structures and perform complex operations. Bash script offers several types of loops such as for, while, until etc. Moreover, one can use any loop within another loop to create a nested loop structure for performing more complex tasks with few lines of code.

Syntax Description
for variable in list; do
# Code
done
Iterate over the list and execute code for each element of the list
while condition; do
# Code
done
Execute code repeatedly as long as the condition is true
until condition; do
# Code
done
Execute code repeatedly until the condition becomes true
select variable in list; do
# Code
done
Execute code based on the choice that the variable takes from the list
continue Skip the current iteration of a loop and continue with the next iteration
break Terminate a loop based on certain condition

Examples of control structures available in Bash programming language:

for i in {1..5}; do
 echo "Current value of the number is: $i"
done
count=1
while [ "$count" -le 5 ]; do
 echo "Current value of count is: $count"
 count=$((count + 1))
done
count=1
until [ "$count" -gt 5 ]; do
 echo "Current value of count is: $count"
 count=$((count + 1))
done
options=("Option 1" "Option 2" "Option 3")
select choice in "${options[@]}"; do
 echo "You selected: $choice"
 break
done

Functions

Functions offer several advantages in Bash scripting. They promote code reusability. One can define a function once and use it multiple times. This enhances productivity, code readability and maintainability, as functions help break down complex tasks into smaller, modular units.

Syntax Description
function_name() {
# code
}
Declare a function with the specified function name
function_name Call a function with the specified function name
local var_name=value Declare a local variable inside a function
return Exit a function and return a value of the calling function

Demonstration of defining a function and calling the function in Bash script.

# Define a function that calculates the square of a number

calculate_square() {
local num=$1
local square=$((num * num))
return $square
}
# Call the function and store the result in a variable
result=calculate_square 5
echo "The square is: $result"

Arithmetic Operations

Bash script has built-in capabilities of performing arithmetic operations on numeric values. One can use arithmetic expressions and operators to perform calculations. Here are the key aspects of arithmetic operations in Bash.

Syntax Description
+ Addition
Subtraction
* Multiplication
/ Division
% Modulus or remainder
** Raise to a power
((i++)) Increment a variable
((i–)) Decrement a variable

Arithmetic Conditional Operators

Arithmetic conditional operators are usually used on two numbers to determine if a certain condition is true or false.

Syntax Description
-lt Equals to mathematical < operator (less than)
-gt Equals to mathematical > operator (greater than)
-le Equals to mathematical <= operator (less than equal)
-ge Equals to mathematical >= operator (greater than equal)
-eq Equals to mathematical == operator (equal)
-ne Equals to mathematical != operator (not equal)

Boolean Operators

Boolean operators include and &&, or || and not equal to !. These operators allow us to test if two or more conditions are true or not.

Syntax Description
&& Logical AND operator
|| Logical OR operator
! NOT equal to operator

String Manipulation

We can manipulate and transform strings to achieve various tasks in Bash script. It provides a variety of techniques for string manipulation. Here are some key aspects of string manipulation:

Syntax Description
concatenated=”$str1 $str2″ Concatenate the variables set in str1 and str2
substring=${str:n} Extracts a substring from n-th index to till the end of the string that stored in variable str
substring=${str:0:5} Extracts substring from 0-th index to 5-th index of the string that stored in variable str
length=${#str} Find the length of the string that stored in variable str
[[ $str == *”World”* ]] Returns True if the string stored in variable str contains the word World
replaced=${str/World/Universe} Replaces the first occurrence of ‘World’ with ‘Universe’ within the string stored in str variable
trimmed=${str##*( )} Trims leading whitespace of the string stored in str variable
trimmed=${trimmed%%*( )} Trims trailing whitespaces of the string stored in trimmed variable

String Comparison Operators

We can use string comparison operators to determine if a string is empty or not, and to check if a string is equal, less, or greater in length to another string.

Syntax Description
= equal
!= not equal
< less then
> greater then
-n str1 string str1 is not empty
-z str2 string str2 is empty

Conclusion

In conclusion, the Bash scripting cheat sheet of this article is a valuable resource for all levels of scriptwriter as it covers the key aspects of Bash programming. I believe the cheat sheet will help the reader to write robust, versatile and customized Bash scripts. However, Bash scripting is vast and has limitless tools and topics. So never stop to explore additional resources and documentation to deepen your understanding and proficiency in Bash scripting.

People Also Ask

What does $@ mean in Bash?

$@ is a special variable in bash that indicates all the arguments passed to the script or function. It holds each argument as a separate word.

Why is bash used?

Bash is used due to its flexibility, scripting power, and its widespread use in the Unix/Linux ecosystem. It has become the go-to shell for a lot of users and system administrators because of its robustness and compatibility.

What is the full form of Bash?

Bash stands for Bourne Again Shell. It is the default shell of most Linux/Unix-like operating systems.

Which scripting language is best?

There is no straightforward answer to this question. In fact, it depends on your project’s needs and your personal preference. For example, if you need to automate the command-line task in a Unix/Linux environment, you can opt for the Bash scripting language. Other popular scripting languages include Javascript, Python, PHP, Perl, etc.

5/5 - (51 votes)
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux

Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment