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

# 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: "

# 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: "

# 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=("" "" ""

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

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: "

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

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)

# 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

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