Bash Scripting Examples

TL;DR

## Hello World: Your First Bash Script

#!/bin/bash

# This is a bash script to print "Hello, World!" to the terminal
echo "Hello, World!"

## Echo Commands

#!/bin/bash
# This script displays a greeting
echo "Hello, world!"
echo "Today is $(date)."
echo "Your current directory is: $(pwd)"
echo "Your PATH is: $PATH"

## Using Variables

#!/bin/bash
# This script uses variables to store and display information

greeting="Welcome"
user=$(whoami)
directory=$(pwd)

echo "$greeting, $user! You are currently in the directory: $directory."

## Reading User Input

#!/bin/bash
# This script reads user input and displays a personalized message

echo "Please enter your name: "
read name
echo "Hello, $name! Welcome to bash scripting."

echo "What is your favorite programming language? "
read language
echo "Great choice! $language is a lot of fun."

## Reading User Input (Hidden Characters)

#!/bin/bash
# This script securely reads a password from the user

echo "Enter your password:"
read -s password
echo "Password accepted. Processing..."

# The script would typically proceed to validate or use the password securely

## If-else Statement

#!/bin/bash
# This script checks if the user is the root user and responds accordingly

if [ $(whoami) = "root" ]; then
    echo "You are running this script as the root user."
else
    echo "You are not the root user. Please run this script with sudo."
fi

## Case Statement

#!/bin/bash
# This script provides a menu for the user and executes commands based on the user's choice

echo "Select an option:"
echo "1) List files"
echo "2) Print current directory"
echo "3) Exit"
read option

case $option in
  1) echo "Files in directory:" && ls ;;
  2) echo "Current directory:" && pwd ;;
  3) echo "Exiting script." && exit 0 ;;
  *) echo "Invalid option selected. Exiting." && exit 1 ;;
esac

## Adding Comments

#!/bin/bash
# This script demonstrates the use of comments

# Define a variable
greeting="Hello" # This is an inline comment

# Display a message
echo $greeting, world! # This command prints "Hello, world!" to the terminal

# The following line is commented out and won't execute
# echo "This won't run."

echo "Script complete." # Indicate the script has finished

## Logical AND (&&)

#!/bin/bash
# This script checks for a file and then displays its contents if it exists

filename="example.txt"
[ -f "$filename" ] && echo "$filename exists." && cat "$filename"

## Logical OR (||)

#!/bin/bash
# This script attempts to create a directory and handles failure gracefully

dirname="new_directory"
mkdir "$dirname" || echo "Failed to create $dirname. It may already exist."

## For Loop

#!/bin/bash
# This script demonstrates a for loop

for fruit in apple banana cherry; do
  echo "I like $fruit!"
done

## While Loop

#!/bin/bash
# This script demonstrates a while loop

counter=1
while [ $counter -le 5 ]; do
  echo "Counter is $counter"
  ((counter++))
done

## Reading Command Line Arguments

#!/bin/bash
# This script prints the first command line argument

echo "The first argument is: $1"

## Reading Command Line (Named) Arguments

#!/bin/bash
# This script demonstrates reading named command line arguments

while [[ "$#" -gt 0 ]]; do
  case $1 in
    -u|--username) username="$2"; shift ;;
    -p|--password) password="$2"; shift ;;
    *) echo "Unknown parameter passed: $1"; exit 1 ;;
  esac
  shift
done

echo "Username: $username, Password: $password"

## Reading from a File

#!/bin/bash
# This script reads each line from a file

filename='list.txt'
while IFS= read -r line; do
  echo "Line: $line"
done < "$filename"

## Writing to a File

#!/bin/bash
# This script writes messages to a file

echo "Hello, world!" > output.txt
echo "This is a new line." >> output.txt

## Check if File Exists

#!/bin/bash
# This script checks if a file exists

filename="example.txt"
if [ -f "$filename" ]; then
  echo "$filename exists."
else
  echo "$filename does not exist."
fi

## Check if Directory Exists

#!/bin/bash
# This script checks if a directory exists

dirname="example_dir"
if [ -d "$dirname" ]; then
  echo "$dirname exists."
else
  echo "$dirname does not exist."
fi

## Create File if Not Exists

#!/bin/bash
# This script creates a file if it does not exist

filename="newfile.txt"
if [ ! -f "$filename" ]; then
  touch "$filename"
  echo "$filename created."
else
  echo "$filename already exists."
fi

## Create Directory if Not Exists

#!/bin/bash
# This script creates a directory if it does not exist

dirname="newdir"
if [ ! -d "$dirname" ]; then
  mkdir "$dirname"
  echo "$dirname created."
else
  echo "$dirname already exists."
fi

## Sleep Command

#!/bin/bash
# This script demonstrates the use of sleep for timing

echo "Starting task..."
sleep 3 # Pauses for 3 seconds
echo "Task completed after a pause."

for i in {1..5}; do
  echo "Iteration $i"
  sleep 1 # Pause for 1 second between iterations
done

echo "Script ended with timed intervals."

## Wait Command

#!/bin/bash
# This script demonstrates the use of wait to synchronize background tasks

echo "Starting background tasks..."
sleep 5 &
pid=$!
sleep 3 &
sleep 2 &

wait $pid # Waits only for the first sleep command to complete
echo "The longest sleep of 5 seconds is complete."

wait # Waits for all remaining background jobs to finish
echo "All background tasks are complete. Continuing with the script..."

## Working with Functions

#!/bin/bash
# This script demonstrates the use of a function

greet_user() {
  echo "Hello, $1" # $1 refers to the first argument passed to the function
}

# Call the function with "Alice" as the argument
greet_user "Alice"

## Error Handling

#!/bin/bash
# Error handling example

create_directory() {
  mkdir $1
  if [ $? -ne 0 ]; then
    echo "Error: Failed to create directory $1"
    exit 1
  else
    echo "Directory created successfully."
  fi
}

create_directory "newdir"

## Command-Line Arguments

#!/bin/bash
# Command-line arguments example

echo "Script Name: $0"
echo "First Argument: $1"
echo "Second Argument: $2"
echo "All Arguments: $@"
echo "Number of Arguments: $#"

## String Concatenation

#!/bin/bash
# String concatenation example

first_name="John"
last_name="Doe"
full_name="$first_name $last_name"

greeting="Hello, $full_name!"

echo $greeting
Leave a message