Bash Scripting Cheat Sheet
Defining a variable
Displaying a variable
Command output to a variable
Conditional Statements and Flow Control
Bash introduces conditional statements (if-else
), allowing scripts to make decisions based on specific conditions or comparisons. Combined with logical and comparison operators, conditional statements facilitate decision-making processes, error handling, and more complex script flows.
Using if-else
condition
if-else
conditionLoop Constructs: Automating Repetition
Loop constructs, such as for
and while
, empower Bash scripts with repetition capabilities. Through loops, scripts can automate iterative tasks, from file processing to data generation and analysis, boosting productivity and efficiency.
Using a for
loop
for
loopUsing a while
loop
while
loopFunctions: Modular Scripting
Functions are a key component of modular design principles. They act as containers for reusable code segments, improving organisation, readability, and maintainability. By incorporating functions, you can adopt a modular approach to scripting challenges.
Defining a function
Calling a function
Pipelines and Redirection: Streamlining Data Flow
Bash scripting utilises pipelines (|
) and redirection (>
, >>
) to combine commands. These allow scripts to channel command outputs, streamline data flow, and manage command outputs.
Using a pipeline
Redirecting output to a file
Exploring More Advanced Constructs
Beyond the fundamentals, Bash scripting can be used with advanced constructs, such as case
statements, arrays, and parameter expansions.
Using a case
statement
case
statementUsing arrays
The example script above performs two main tasks:
Using a
case
statement: It checks the value of the first command-line argument ($1
) and executes different actions based on its value. If the argument is “start,” it prints “Starting…”; if “stop,” it prints “Stopping…”; for any other value, it prints “Invalid option.”Working with arrays: The script defines an array named
colors
with elements “red,” “green,” and “blue.” It then prints the first element of the array, which is “red,” using${colors[0]}
.
Last updated