Basics of Bash Scripting

Programming Apr 3, 2020

A Bash script is a plain text file that contains a series of commands. These commands are a mixture of commands we would normally type ourselves on the command line (such as ls or cp for example) and commands we could type on the command line but generally wouldn’t.

Topics covered

  • grep
  • cut
  • tr
  • script writing
  • for loops
Command that pings Google’s IP address one time:
[email protected]:~# ping -c 1
PING ( 56(84) bytes of data.
64 bytes from icmp_seq=1 ttl=128 time=3.65 ms

--- ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 3.653/3.653/3.653/0.000 ms

The objective of exercise: Grab the IP address from the line containing the text “64 bytes”

  • First, we are going to be making use of a tool called grep to retrieve the entire line as seen below
[email protected]:~# ping -c 1 | grep “64 bytes” 64 bytes from icmp_seq=1 ttl=128 time=3.67 ms
  • Next up, we are going to be using a tool named cut on top of grep to be able to get only the IP address which is our final objective
[email protected]:~# ping -c 1 | grep “64 bytes” | cut -d “ “ -f 4
  • Now we have a small little problem, we have a semicolon at the end of the output. If we were to use that output to ping the IP that wouldn’t work due to the extra character. Let's take a look at how we can further edit the output using a tool named tr
[email protected]:~# ping -c 1 | grep “64 bytes” | cut -d “ “ -f 4 | tr -d “:”

The objective of the script: Create a ping sweeping script similar to [nmap -sn]

  • Now that we have all that information, let's move on to creating a simple bash script that will ping sweep a subnet for alive hosts!
[email protected]:~/scripts# cat 
if [ "$1" == "" ]
        cat /root/scripts/sign
        echo "You cant leave your network address blank :("
        echo "It should look something like: ./ 192.168.1"
        cat /root/scripts/sign
        cat /root/scripts/process
        echo ""
        echo "The following are the alive hosts....."
        for ip in `seq 1 254`;do
                ping -c 1 $1.$ip | grep "64 bytes" | cut -d " " -f 4 | tr -d ":" &
echo ""
echo ""
  • The first if loop is to check if the user had entered the variable, in our case the network address.
  • If that loop meets its criteria we then proceed to iterate through the whole subnet by adding values from 1 all the way to 254 behind the network address provided by the user.
  • If there is no input entered by the user, the script will terminate, else it will iterate through the subnet and come up with the hosts that are alive!

Final Product

  • Use case 1: user ran the script without an argument
  • Use case 2: user ran the script with a valid network address as the argument