Quick Links
Bash scripting is one of the most popular, accessible ways of programming your Linux computer. These simple script examples will help you understand the process and introduce you to the basics of Bash programming.
1. How to Print Hello World in Bash
The Hello World example is a great way of learning about any programming language, and Bash is no exception.
Here’s how to print “Hello World” using Bash:
TheShebang command(#!/bin/bash) is essential as the shell uses it to decide how to run the script. In this case, it uses the Bash interpreter.
2. Create a Directory by Reading Input
From your scripts, you can run any program that you might normally run on the command line. For example, you can create a new directory from your script using themkdircommand.
3. Create a Directory Using Command Line Arguments
As an alternative to reading input interactively, most Linux commands support arguments. You can supply an argument when you run a program, to control its behavior.
Within your script, you can use $1 to refer to a special variable that contains the value of the first argument. $2 will refer to the second argument, and so on.

You may be wondering what happens if you run the script without supplying an argument at all. Try it and see; you should receive an error message that starts “usage: mkdir”:
Without any command-line arguments, the value of$1will be empty. When your script callsmkdir, it won’t be passing an argument to it, and the mkdir command will return that error. To avoid this, you can check for the condition yourself and present a more friendly error:

When you run this new version of the script, you’ll get a message if you forget to include an argument:
4. Delete a File Using a Bash Function
If you find yourself repeating the same code, consider wrapping it in a function. you may then call that function whenever you need to.
Here’s an example of a function that deletes a given file.

When you call a function, it will set the special$?value with the exit status of the last command it runs. The exit status is useful for error checking; in this example, you can test whether thermcommand succeeded:
5. Create a Basic Calculator for Arithmetic Calculations
This final example demonstrates a very basic calculator. When you run it, you’ll enter two values, then choose an arithmetic operation to carry out on them.
Here’s the code forcalc.sh:
Note the use ofcase … esacwhich is Bash’s equivalent of the switch statement from other languages. It lets you test a value—in this case, thechoicevariable—against several fixed values and run associated code.
This script uses thebccommand to carry out each calculation.

