Linux Basics

75 / 107

Writing first shell script

A shell script is a file containing a list of shell commands which would otherwise could be run individually on the OS shell prompt.

Note: In Unix, the extension doesn't dictate the program to be used while executing a script. It is the first line of the script that would dictate which program to use. The first line starts with the sequence of two characters #! that is called shebang. This is followed by the program that tells the operating system which interpreter to use to parse the rest of the file.

The Shebang interpreter directive takes the following form:

#!interpreter [arguments]

In the example below, the program is /bin/bash which is a Unix shell.

Let's create a simple command that prints two words:

  1. Open a text editor to create a file

  2. Write the following into the editor:

    echo "hello $name world"

If you want that every variable must be declared before it can be used, then add set -u at the top of the script after the shebang line.

set -u
echo "hello $name world"
echo $surname
  1. Press Ctrl+X to save and then Y
  2. It will ask for a filename, check if its If not enter the same filename.
  3. Hit Enter key to exit

  4. Now, by default, it would not have executable permission. You can make it executable like this:

    chmod +x
  5. To run the script, use:


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...