Bash Scripting Expanded, Your Guide to Scripting Mastery

12 December 2023 8 minutes Author: Cyber Witcher

The Bash Bible: Your Personal Guide to the World of Scripting

This article covers the basic concepts, syntax, and structure of the Bash language, providing clear explanations and practical examples to help you understand and apply this knowledge in real-world scenarios. From basic syntax and using variable comments, executing commands, input/output, understanding different data types like strings, numbers, and arrays, this tutorial covers everything you need to be able to program effectively in Bash. Special attention is paid to string manipulation techniques, which are an important part of Bash scripting. This article will be a valuable resource for both beginners and experienced developers looking to deepen their knowledge of Bash Scripting.

In this article, you will find a complete Bash Scripting Cheat Sheet, which is the perfect guide for anyone who wants to learn or improve their Bash skills. From basic syntax rules to advanced programming techniques, this tutorial covers important aspects of Bash, including the use of variables, data management, input/output, working with different data types, and string manipulation techniques. It provides clear explanations and examples to help you understand and use Bash effectively for your programming tasks.

Bash Scripting Chet Shet

Bash (Bourne Again SHell) is a powerful and widely used language. It provides many features and tools for automating tasks, managing files, processing data and much more. However, remembering all the syntax and commands can be difficult. This Bash scripting cheat sheet serves as a quick reference to the basic concepts, syntax, and basic structure of the language. It covers a range of topics, including variables, conditions, loops, functions, and string operations in Bash scripts. Each chapter contains clear explanations and practical examples to help you understand the concepts and structure of the language.

Download the Bash Scripting Cheat Sheet

PDF (4 pages)

CLICK HERE

DOC (4 pages)

CLICK HERE

ZIP (pdf, docx, png)

CLICK HERE

The syntax of a programming language defines a set of rules and conventions that govern the writing of programs. Each programming language has its own syntax and structure. The syntax of Bash scripts is simple and easy to understand. To write a correct and functional script, one must have a solid understanding of operator, variables, data types, control structure, etc.

Basic syntax

If you’re a complete beginner and have never written any Bash scripts, here’s where you can start. This chapter covers the basic syntax of Bash scripting, including Shebang scripts and the Bash exit path.

Comments

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

Single and multi-line comments in Bash scripts:

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 important part of any programming language. Bash script variables allow you to dynamically store, manipulate, and retrieve data. This chapter will cover variable structure, accessing a variable’s value in a Bash script, and other variable-related basics.

Different types of variables and properties of variables.

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

Execution of the command

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

Command execution, command substitution, and output redirection 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 at runtime. Additionally, it can read input from files and can redirect output to a file. This allows the user to process data from external sources or create output files containing the results of script execution.

Examples of prompt input and 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 scripting offers several data types for handling other information in scripts. Bash data types are mainly String, Numeric, and Array.

Different data types in the 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 operators

A conditional statement in Bash scripting allows us to control the flow of a program based on a certain condition. There are three main types of conditional statements in Bash scripts. These are the 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.

 

Structure of conditional statements in Bash scripts.

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

Cycles

Loops are an important feature of any programming language. They provide a way to automate repetitive tasks, repeat data structures, and perform complex operations. Bash scripting offers several types of loops such as for, while, until, etc. Alternatively, you can use any loop within another loop to create a nested loop structure to perform more complex tasks with just a few lines of code.

Examples of control structures available in the 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 reuse. You can define a function once and use it multiple times. This improves performance, code readability, and maintainability because functions help break down complex tasks into smaller, modular units.

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

# Define a function that calculates the square of a number

calculate_square() {
local num=$1
local square=$((num * num))
return $square
}

Arithmetic operations

The Bash script has built-in capabilities to perform arithmetic operations on numeric values. Arithmetic expressions and operators can be used to perform calculations. Here are the key aspects of arithmetic operations in Bash.

Arithmetic conditional operators

Arithmetic conditional statements are typically used on two numbers to determine whether a certain condition is true or false.

Logical operators

Logical operators include and && or || and is not equal to !. These statements allow us to test whether two or more conditions are true or not.

String manipulation

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

String comparison operators

We can use string comparison operators to determine whether a string is empty or not, and to check whether a string is equal to, less than, or greater than the length of another string.

Conclusion

As such, the Bash scripting cheat sheet provided in this article is a valuable resource for writers of all levels, as it covers important aspects of Bash programming. I believe the cheats will help readers write reliable, versatile, and customizable Bash scripts. But Bash scripts are huge and have endless Tools and Themes. That’s why don’t stop exploring Additional Resources and Documentation to love understanding and mastering Bash scripting.

Other related articles
Automation and scriptsServices
Read more
Bash scripts
Discover the benefits of using the Bash command line interface over the GUI. Manage your computer's operating system efficiently with the Bash scripting language without the need for menus or windows.
221
0
Found an error?
If you find an error, take a screenshot and send it to the bot.