Beginners Guide To BASH - Part 1 - Hello World

Write a simple script and learn the basics of the Bash shell for Linux

Most Linux distributions ship the Bourne Again Shell—usually just called Bash—by default. Even the Windows Subsystem for Linux supports Bash.

What Is Bash?

A shell is a command-line interpreter. It's intended to work in a text-only mode and support interactive commands and scripts. Linux offers several different shells. Bash is common and well-known, but others include ASH, CSH, KSH, and ZSH.

Bash main menu on computer

How Do I Write a Bash Script?

The most straightforward way to develop simple Bash scripts is to work from the shell. Most Linux distributions include a graphical user interface, but some don't—including WSL and any server-based installation you access remotely.

To access the shell (sometimes called the command line interface or the terminal window), run it from the Window Manager main menu.

Bash main menu

Most modern Linux distributions support the Ctrl+Alt+T hotkey to launch a shell window within the GUI.

You need two things to write a Bash script:

  • Bash: From the shell, execute the command which bash. If the result is something like /bin/bash or an equivalent, you're good to go. If you get a blank response, then Bash is likely not installed on your system, or your user account doesn't allow you access to it.
  • A text editor: Use the text editor you're most comfortable with. Many modern distributions include GNU nano, which is user friendly. Virtually every distribution includes the tried-and-true vi editor. Use the which command to verify which editor is installed.

Vi isn't the most intuitive text editor, but it's almost always present by default.

Create the Hello World Script in Bash

To create a "Hello World" script, invoke your text editor from the shell prompt:

vi hello.sh

Input the following lines of text:

#!/bin/bash
echo "hello world"

Then, save the file. It saves to your home directory.

Bash script in vi

This simple script offers two lines. The first tells Linux that you developed a Bash script (meaning that what follows is a script and that Bash is the correct interpreter to execute it). The second line gives a command—it echoes the text hello world to the console window.

If you've never worked in Vi before, you need to do two things. First, after the editor loads, press I to enter Insert mode. Then type your text. Don't worry about all the tildes on the screen; they just indicate blank lines. When you're done editing, press Esc to exit Insert mode and enter Command mode. When you're in Command mode, press :wq to save the file and exit the editor.

Run the 'Hello World' Script in Bash

To run your script, execute the following command:

bash hello.sh

and you'll see hello world printed below the shell prompt.