Bash programming/Introduction

From Wikiversity
Jump to navigation Jump to search

Pre-requisites[edit | edit source]


  • may need some facility with a text editor such as Gedit or vi/vim, emacs, nano, jed, Visual Studio Code, Atom, etc,
  • must have access to an operating system with a *nix terminal to enter commands. On Windows, there are a number of *nix emulators. At this time cygwin is popular.


  • echo
  • find
  • more
  • | -- the pipe

New Concepts[edit | edit source]

When you complete this section you will be able to

  • write, display, and use shell aliases,
  • write, display, and use shell functions,
  • explain the distinction between a sell script and a function

Shebang: #![edit | edit source]

Shebang (#!) is the character sequence consisting of the characters number sign and exclamation mark (#!) at the beginning of a script and make program loader to parses the rest of the line as an interpreter directive. Your bash script will have to start with one of the following examples.


  • #!/bin/bash
  • #!/usr/bin/env bash

Bash Shell[edit | edit source]

The Bash Shell is the command interface to many Unix operating system implementations. It is available as either an optional or default shell on most Unix variants. If you administer your system, you likely know your command terminal shell. If not, execute this command to see which shell you use:

$ echo $SHELL

If you see /bin/bash, then you are a bash shell user.

When writing programs for the Bash Shell, you are creating a file to be executed by the shell. Bash programs are similar in nature to Batch scripts (or BAT files) in Microsoft Windows. Any *nix operating system, and hence the shell program allows for much greater functionality.

Bash programs are only a series of command-line commands. That is, there is nothing that can be done in a bash program that cannot be done by individually entering the commands at the command line. In fact, if you were to take a Bash program (or script), print it out, and re-enter the commands, one by one at the Bash prompt, you would get the exact same result.

Another user command which we'll call the Programmer's Birth Announcement is:

$ echo "Hello World"   # produces
Hello World            # on your terminal
$ ...

There are two ways to write a shell program, traditionally as a single script, since early shells (/bin/sh) did not have functions, and more recently as a composition of functions, since the function became available in ksh, and is now readily used in bash.

Scripts have the advantage of putting all the commands in a single file, the disadvantage of needing a text editor to begin.

Functions have the advantage of working directly from the command line: you can write and test a function without having to edit a file. The disadvantage of using functions is still the text editor To re-use a function for alter terminal sessions, you need to save it in a file, and recall it when you log in again. For now, that's a later lesson.

Bash Function[edit | edit source]

After typing a number of individually entered commands at the command prompt, your usage pattern begins to emerge. A collection of single commands can be collected in a function. Let's start with the single command:

$ helloWorld () { echo "Hello World!"; }  # write the function
$ helloWorld                              # use it
Hello World!

Later sessions will deal with the syntax of the function.

Bash Script[edit | edit source]

A sample bash script can be as simple as this:

echo "Hello World!"

Alternatively, it can be as complex as script designed to install and configure whole operating systems or troubleshoot problematic servers. A typical Bash Script is used to automate monotonous tasks like scanning directories and deleting automatically backed up files, or setting permissions to new files.

To begin the coding of a Bash Script, use a text editor to start off the file with:


This is called the "hash bang" or she bang line and specifies the location of the program to be used to interpret the rest of the contents. In this case, you are specifying location of the Bash shell. Note: this location varies by Unix variant, and depends on the placement of the bash binary. This hash-bang declaration that is present at the top of most Bash Files. It is standard practice to include this line in all your Bash Scripts, though careful reading of the reference shows it's not absolutely necessary. We'll resolve this later.

A User Command[edit | edit source]

Another example, this time of one of those user commands, which repeated typing at the command line may become tedious, if not error-prone.

This example uses the find command to find your TXT files, first using the alias feature, then as a function.

The Alias[edit | edit source]

Aliasing allows complex commands to be simplified by using another sequence. Next, you can call the alias to do work -- an alias is used like a constant from other programming languages, except it's used to execute programs.

Read this alias article on Wikipedia. Refer to the Unix paragraph.

Write the commands that need to be performed, such as:

alias txtfiles="find $HOME -name '*.txt'"
txtfiles  | more         # on your own computer

Create that alias, then Exercise the examples in the Viewing currently defined aliases section:

  • list all current aliases
  • list in a format to recreate the alias
  • display a single alias

Do your results agree with your expectations?

Finally, note the alias article, Alternatives section. That section introduced one other feature of the shell: symbolic links, to be covered later. Importantly, that section compares the two other features of this current section: Shell scripts and Shell functions.

The Function[edit | edit source]

Again alternatively, the function provides similar functionality:

$ txtfiles () { find $HOME -name '*.txt; }     # defines a function
txtfiles  | more                    # uses it

If executing the alias and function in succession, then depending in which was first, you will have to

$ unalias txtfiles     # or
$ unset txtfiles       # if a function

Refer again to the Wikipedia article on the shell alias, Alternatives. One important facet to take note of is the command built-in. Literally the word command protects a function name or alias, to use the fundamental command, neither an alias nor a function.

At this point, following the examples, you have two working functions. To display them, use this command:

$ declare -f helloWorld txtfiles 
...   the function bodies are displayed

Execute that command. Does your output match your expectation?

In the next section of the course, we'll examine the notion of a function body more closely, and learn how to save and recall functions so we think of them as ordinary commands.

In Summary[edit | edit source]

Assessment[edit | edit source]

1 What's the name of the function to display "Hello World!"?

Hello World
hello World!

2 The command to long-list files in the current directory is "ls -l"

Fill in the blanks to write an alias named "ll" to do just that



Open for later sessions[edit | edit source]

  • Using a text editor to save files including scripts, functions, and alias
  • what about environment variables
  • complete function syntax
  • the symbolic link
  • the terminal shell (and the need or not for sh-bang)
  • how to reload functions, and access script.