DEV Community

Cover image for Bash Scripting: A Comprehensive Guide
Rahul Kumar
Rahul Kumar

Posted on

Bash Scripting: A Comprehensive Guide

Bash is a powerful scripting language that runs on Unix-like systems, including Linux and macOS. It's a versatile tool for automating tasks, managing files, and interacting with the system.

Basics

Shell Script: A text file containing a sequence of Bash commands.
Shebang: The first line of a script, indicating the interpreter to use (e.g., #!/bin/bash).
Execution: Make the script executable (chmod +x script.sh) and run it (./script.sh).

Essential Commands

echo: Prints text to the terminal.
read: Reads input from the user.
if-else: Conditional statements.
for: Loops through a list of items.
while: Loops as long as a condition is true.
case: Matches a value against patterns.
functions: Reusable blocks of code.

Variables

Declaration: variable_name=value
Usage: echo $variable_name
Types: String, integer, floating-point.

File Operations

Creating: touch filename
Deleting: rm filename
Copying: cp sourcefile destfile
Moving: mv sourcefile destfile
Listing: ls
Directing: cd directory

Input/Output

Reading: read variable
Writing: echo "text" > filename
Appending: echo "text" >> filename

Arithmetic Operations

Basic: expr 2 + 3
Shell Arithmetic: (( result = 2 + 3 ))

Control Flow

if-else:



Bash

if [ condition ]; then
    commands
elif [ condition ]; then
    commands
else
    commands
fi


Enter fullscreen mode Exit fullscreen mode

for loop:



Bash

for variable in list; do
    commands
done


Enter fullscreen mode Exit fullscreen mode

while loop:



Bash

while [ condition ]; do
    commands
done


Enter fullscreen mode Exit fullscreen mode

case:



Bash

case variable in
    pattern1)
        commands ;;
    pattern2)
        commands ;;
    *)
        commands ;;
esac


Enter fullscreen mode Exit fullscreen mode

Functions

Defining:



Bash

function function_name() {
    commands
}


Enter fullscreen mode Exit fullscreen mode

Calling: function_name

Examples

Hello, World:



Bash

#!/bin/bash
echo "Hello, World!"


Enter fullscreen mode Exit fullscreen mode

Simple calculator:



Bash

!/bin/bash
echo "Enter two numbers:"
read num1 num2
result=$((num1 + num2))
echo "The sum is: $result"

Enter fullscreen mode Exit fullscreen mode




Regular Expressions

Pattern Matching: Used for complex string manipulation and searching.
Syntax: grep 'pattern' file
Example: Find lines containing email addresses: grep '[[:alnum:]]+@[[:alnum:]]+.[[:alnum:]]+' file

Pipes and Redirection

Pipes: Connect the output of one command to the input of another.
Example: List files, sort them by size, and print the top 10: ls -l | sort -n -k 5 | head -n 10
Redirection:
">": Overwrite output.
">>": Append output.
"<": Redirect input.

Command Substitution

Executing Commands Within Expressions: $(command) or command
Example: Set a variable to the current date: current_date=$(date)

Arrays

Declaration: array_name=(element1 element2)
Accessing: echo ${array_name[index]}
Example: Create an array of fruits: fruits=("apple" "banana" "orange")

Functions with Arguments

Passing Arguments: function_name arg1 arg2
Accessing Arguments: $1, $2, ...
Example:



Bash
function greet() {
echo "Hello, $1!"
}
greet John

Enter fullscreen mode Exit fullscreen mode




Conditional Expressions

Test Brackets: [ condition ] or [[ condition ]]
Operators: -f (file), -d (directory), -x (executable), -z (empty), -n (non-empty), =, !=, <, >, -eq, -ne, -lt, -le, -gt, -ge
Example: Check if a file exists: if [ -f file.txt ]; then ...

Debugging

Tracing: set -x
Error Checking: if [ $? -ne 0 ]; then ...
Logging: echo "Message" >> logfile

Best Practices

Clarity and Readability: Use meaningful variable names and comments.
Error Handling: Anticipate potential errors and provide informative messages.
Modularity: Break down complex scripts into smaller functions.
Efficiency: Optimize your scripts for performance.

Advanced Topics

Here Documents: Multi-line input within a script.
Getopts: Parsing command-line options.
Signal Handling: Responding to interrupts and signals.
Background Jobs: Running commands in the background.
Shell Options: Customize Bash behavior (e.g., set -e for strict error checking).

https://github.com/Rahul-1999/websetup

Top comments (2)

Collapse
 
jimmymcbride profile image
Jimmy McBride

Great article! Loving seeing quality content about bash scripting like this. Keep it up!

Collapse
 
echoglobal profile image
EchoGlobal

Bash scripting: where a missing semicolon can make you question all of your life choices. :-)