Index


SETTING UP
SHEBANG LINE
COMMENTS
VARIABLES
INPUT/OUTPUT
CONTROL STRUCTURES
FUNCTIONS
FILE OPERATIONS
EXIT STATUS
EXAMPLE
BASH SCRIPT

A BRIEF OVERVIEW

Bash scripting refers to the process of writing and executing scripts using the Bash(short for "Bourne Again Shell") shell. Bash scripting allows users to automate repetitive tasks, write complex commands, and create custom solutions by writing scripts in the Bash programming language.


SETTING UP

Before we start writing Bash scripts, ensure you have a text editor installed (like VSCode, Sublime Text, or Vim) and access to a terminal or command prompt where you can run Bash commands.

SHEBANG LINE

The shebang line (#!/bin/bash) tells the system which interpreter to use for executing the script. Place it at the beginning of your script.
bash
#!/bin/bash


COMMENTS

Comments in Bash start with # and are used for documentation or to add explanations within the script.
bash
# This is a comment explaining what the script does


VARIABLES

Declare variables to store data. Variable names are case-sensitive and should start with a letter or underscore.
bash
name="John"
age=30

To access the value of a variable, prefix its name with $.
bash
echo "Hello, $name! You are $age years old."


INPUT/OUTPUT

User Input: Use read to get input from the user.
bash
echo "What's your name?"
read name

Output: Use echo to display output.
bash
echo "Hello, $name!"


CONTROL STRUCTURES

if Statement: Use if, elif, and else for conditional execution.
bash
if [ "$age" -ge 18 ]; then
    echo "You are an adult."
else
    echo "You are a minor."
fi

for Loop: Iterate over a list of items.
bash
for i in {1..5}; do
    echo "Iteration $i"
done

while Loop: Execute a block of code while a condition is true.
bash
count=0
while [ $count -lt 5 ]; do
    echo "Count: $count"
    ((count++))
done


FUNCTIONS

Define functions to group code into reusable blocks.
bash
greet() {
    echo "Hello, $1!"
}

greet "Alice"


FILE OPERATIONS

Perform file-related operations like reading, writing, and executing files.
bash
# Read from a file
while read line; do
    echo "Line: $line"
done < "file.txt"

# Write to a file
echo "Some data" > "output.txt"

# Execute a file
chmod +x script.sh
./script.sh


EXIT STATUS

Every command in Bash returns an exit status. You can check this status using the $? variable.
bash
ls /nonexistent_dir
if [ $? -ne 0 ]; then
    echo "Directory does not exist."
fi


EXAMPLE

Here's a simple example of a Bash script that incorporates these concepts:
bash
#!/bin/bash

# Function to greet a person
greet() {
    echo "Hello, $1!"
}

# Main script starts here
echo "What's your name?"
read name

greet "$name"

if [ "$name" == "Alice" ]; then
    echo "You're awesome!"
elif [ "$name" == "Bob" ]; then
    echo "You're cool too!"
else
    echo "Nice to meet you, $name."
fi
--- End of Blog ---