>_ IzzyLab

Hands-on task

This task is step 1 of the course “Your first bash script”

Your first script: shebang and running it

easy~5 min

Write your first script — the file /root/hello.sh. Its first line must be a shebang saying that the script is run by bash. After it comes a command that prints exactly one line:

Hello from my first script

Make the script executable and run it as a program — from /root with ./hello.sh.

What you'll practise:
  • bash scripts
  • shebang
  • chmod
  • running a script

Topic breakdown

A script is a text file with commands that the shell runs one after another, top to bottom. Anything you type in the terminal can go into a script and be run with a single command.

The first line of a script is the shebang: the characters #! and the path to the program that will run it. For bash that's #!/bin/bash (or #!/usr/bin/env bash). The shebang must be at the very start of the file — no blank lines or spaces before it.

For example, the script /root/today.sh:

#!/bin/bash
echo "Today is:"
date

There are two ways to run it:

  • bash today.sh — explicitly ask bash to run the file; no execute permission needed;
  • ./today.sh — run the file as a program. For that the file needs execute permission (chmod +x today.sh), and the system learns from the shebang what to run it with.

./ means "the file in the current directory": plain today.sh makes bash look in the system directories from PATH, and it won't find it there.

It's easiest to create the file in an editor: nano today.sh — type the text, Ctrl+O and Enter save it, Ctrl+X closes the editor.

What's checked

  1. /root/hello.sh created
  2. The first line is a bash shebang
  3. The script has execute permission
  4. ./hello.sh prints the line from the task

What it looks like