Bash scripting: From basics to know-it-enough in ten minutes.

This is a pretty random post, but thought I should write a basic bash script tutorial that gets us up and running in no time. The best way to go about this is a series of challenges in increasing difficulty.

1) Write a bash command to store the current directory’s contents in a file.

Hint 1: The command ls lists what’s in the current directory. To store it in a file, we need to execute this command, send the results to the file as input, and then store it.

Hint 2: The backquote ” ` ” operator is used to execute a command (called command substitution). The ” > ”  operator is used as standard input to the next statement.

Answer 1: `echo ls` > ./file1

Answer 2: ls > ./file1

What happens without the backquote? The ls command will not be executed. Instead the word “ls” will directly be stored in the file. Note that file1 is in the current directory, since we used the ” ./ ” operator. Using cat ./file1, you can verify the file contents. We use a single ” > ” here. A double ” >>” operator would append the output to file1 instead.

2) List information of USB devices connected to system.

Hint 1: The command “dmesg” lists all kernel messages, which include statuses about I/O devices, memory, dma etc, since the computer booted up until the present.

Hint 2: The command “grep” searches across the input data to find matches with a certain word, and displays the matching line or phrase.

Answer: dmesg | grep -i “usb”

dmesg’s output is pipelined as input to grep. Grep receives it and searches for the word “usb” without bothering about case, since we’ve used ” -i “.

3) Assign a variable the eth0 IP address of machine using ifconfig.

Hint 1: Use grep and pipelining to extract the IP address. grep flag -o lists only the match instead of the entire line. grep flag -A prints matching line as well as lines following it.

Answer: ipVar=`ifconfig | grep -A 1 ‘eth0’| grep -o ‘inet addr:[0-9]*.[0-9]*.[0-9]*.[0-9]*’ | grep -o ‘[0-9]*.[0-9]*.[0-9]*.[0-9]*’`

ifconfig lists all interfaces with their IP address in the following manner:

eth0      Link encap:Ethernet  HWaddr 00:20:32:4b:48:f4
             inet addr:  Bcast:  Mask: …

The IP address (inet addr) is in the next line following eth0 interface information. We first match “eth0” with grep, and print next line using grep -A 1. This pipelines to grep filtering out the “inet addr” portion, which is then pipelined again to another grep, which extracts the IP address.

Note that regex has been used for extracting the IP address. [0-9]* means one or more digits. ” .” refers to the dot seperating the IP address, and an escape character is used to denote that the special meaning of ” . ” in regex is not considered here.

Verify output using echo $ipVar

Leave a Reply

Your email address will not be published. Required fields are marked *