Beginners Guide To BASH - Part 1 - Hello World

BASH manpage

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.

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 or the terminal window), run it from your window manager's main menu.

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

You'll need two things to write a Bash script:

  1. 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.
  2. 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 you've got installed.

It's not the most intuitive text editor, but it's almost always present by default, so we'll use the vi editor.

Creating the 'Hello World' Script in Bash

Bash script in vi

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.

This simple script offers two lines. The first tells Linux that you've developed a Bash script. 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'll need to do two things. First, after the editor loads, you must press I to enter insert mode. Then you can type your text. Don't worry about all the tildes on the screen; they just show 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.

Running 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 your shell prompt.