Writing a Simple Bash Script

This post demonstrates how to create and run a very simple bash script in Linux using the command terminal. The purpose of the script will be to output all odd numbers in the range of 1-99. The following was performed on an Ubuntu 20.04 instance.

  • Step 1: Create a new file

Use the following command to create a new file with a custom name

nano <newfilename>.sh

Hit enter and a blank new file will open as shown below

  • Step 2: Write a script

Type “i” to enter insert mode (this allows typing in the new file)

All bash scripts begin with:

#!/bin/bash

It’s a good practice to comment the purpose of the script within the script itself so it can be easily understood by others

Do this by placing a ‘#’ and typing a description as seen in the following image

The next line of the script needs to designate the variable to display when the command is run. It must also provide the numerical range for said variable

Do this by entering the following:

for i in {1..99..2} 

This line defines the variable and provides a range for the variable of 1 to 99, starting with 1, and incrementing by 2 at a time.

Now its necessary to tell the script to display the variable in the next line using the “do” and “echo” command as seen below

Finish the script by adding “done” to next line.

Then exit and save the script using Ctrl + X. Type “Y” to confirm and hit enter to return to the original terminal window

  • Step 3: Run the script

Use the the command below to run the newly created script

./nameofscript.sh

It is necessary to give the script permission to execute, otherwise “Permission denied” will be returned when attempting to run it. (Shown below)

To resolve this issue, use the “chmod” command like this:

chmod +x <scriptname>.sh

Now, run the script again and the output should resemble the image below (The user running the script also needs permission to do so. In the example below, the script is run by the root user. The command “sudo su” allows root access.)

Leave a Reply

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