Back to Lab Listing

Lab Objective:

Learn how to write a simple shell script containing multiple commands.

Lab Purpose:

Scripting with Bash is a daily task by many professional Linux administrators. When a task is repetitive, you don’t want to be typing the same list of commands over and over; you want to create a script, and perhaps also schedule that script to run automatically.

Lab Tool:

Ubuntu 18.04 (or another distro of your choice).

Lab Topology:

A single Linux machine, or virtual machine

Lab Walkthrough:

Task 1:

Open the Terminal application, and run your favorite text editor, such as vi or nano. (If you have never used vi or vim, then nano is strongly recommended.)

Create a file with the following contents:

#!/bin/bash

for (( n=0; n<$1; n++ ))

do

echo $n

done

echo “Output from $0 complete.”

Task 2:

Make the file executable (with chmod +x filename), then run it like:

./filename 10

You should see the numbers 0-9 printed out, one at a time. Knowing what the script does now, can you understand it in its entirety? What happens if you fail to pass an argument, or if you pass “gibberish,” like letters instead of a number?

Task 3:

Run your script without an argument. Then run: echo $?

$? is a special variable that references the exit status. In a successful program, the exit status would be 0. Please try it for yourself now. Then edit the script by removing the last echo statement. This script then fails without an argument, returning a different exit status.

Notes:

That first line, starting with #! (called a shebang), denotes what program will be used to interpret your script. Usually, this is /bin/bash, but it can also be another shell like /bin/zsh, or even another programming language like /usr/bin/python.

In this case, you could remove the shebang line because your interpreter is the same (Bash) as the shell you are currently running. But you should always include it because you never know when you might want to share a script with someone who uses a different shell.

Newsletter Subscribe

Stay Informed, Stay Inspired: Subscribe for Cutting-Edge IT-Certification Insights

101 Labs Newsletter