Use basic bash scripting for network automation tasks.

1. Basic Bash Script Structure:

A bash script typically starts with a shebang (#!) line, followed by the path to the Bash interpreter. After that, you can include your script commands.

bashCopy code#!/bin/bash

# Your bash script commands go here

2. Variables:

You can use variables to store and manipulate data in your scripts. For example, to store an IP address:

bashCopy code#!/bin/bash

# Variable declaration
ip_address="192.168.1.1"

# Print the IP address
echo "IP Address: $ip_address"

3. User Input:

You can prompt the user for input using the read command. Here's an example asking the user for an IP address:

bashCopy code#!/bin/bash

# Prompt user for input
echo -n "Enter IP Address: "
read
ip_address

# Print the entered IP address
echo "You entered: $ip_address"

4. Ping Test:

You can use the ping command to test network connectivity. Here's a simple script that pings a specified IP address:

bashCopy code#!/bin/bash

# Prompt user for input
echo -n "Enter IP Address to ping: "
read
ip_address

# Ping the specified IP address
ping -c 4 $ip_address

5. Looping:

You can use loops to iterate over a range of values or a list of items. For example, a loop to ping multiple IP addresses:

bashCopy code#!/bin/bash

# List of IP addresses
ip_addresses=("192.168.1.1" "192.168.1.2" "192.168.1.3"
)

# Loop through each IP address and ping
for ip in "${ip_addresses[@]}"; do
echo "Pinging $ip"
ping -c 4 $ip
done

6. Conditional Statements:

You can use conditional statements for decision-making in your scripts. For instance, a script to check if a host is reachable:

bashCopy code#!/bin/bash

# Prompt user for input
echo -n "Enter IP Address to check: "
read
ip_address

# Check if the host is reachable
if ping -c 4 $ip_address &> /dev/null; then
echo "Host is reachable"
else
echo "Host is not reachable"
fi

7. File Operations:

You can read/write data to files. Here's a script that reads IP addresses from a file and pings each one:

bashCopy code#!/bin/bash

# File with IP addresses (one per line)
file_path="ip_addresses.txt"

# Read IP addresses from file and ping each one
while IFS= read -r ip; do
echo "Pinging $ip"
ping -c 4 $ip
done < "$file_path"

8. Combining Commands:

You can chain multiple commands together. For example, a script that retrieves and displays the public IP address of the machine:

bashCopy code#!/bin/bash

# Use curl to fetch public IP address from a web service

public_ip=$(curl -s ifconfig.me)

# Display the public IP address
echo "Public IP Address: $public_ip"