How to write bash scripts in Linux
Operating systems usually come with some form of scripting language that administrators and power users can use to create custom tools. Unix and Linux are no different and offer many different options. The glue that holds many Linux projects together are Bash scripts. These simple to create, yet incredibly powerful scripts can do everything from remotely backing up entire file systems to creating an LED flash.
Bash scripts behave like scripts in other programming languages. The code executes line by line in a sequence. We can use conditional (selection) logic to change the path our code takes, and code can iterate and repeat code execution until a condition is met or indefinitely.
Bash, the Bourne Again SHell is one of many shells available to Unix and Linux users (Zsh, Ksh, Tcsh, Fish are others) and is commonly installed with many major distributions. We ran Kubuntu 21.10 when writing this tutorial, but the same code will also work on a Raspberry Pi (with Raspberry Pi OS) or almost any other Linux distribution.
In this tutorial, we’ll take our first steps in building Bash scripts with three sample projects. The first is the venerable “Hello World”, then we learn to create interactive scripts, before finally creating a real script to check the status of a site/server. We then go the extra mile and learn how to make our scripts executable and available system-wide.
How to Write a “Hello World” Bash Script
We’ll start simply with “Hello World”. It may seem trivial, but a hello world test is useful for understanding the workflow of creating a Bash script and for testing basic functionality. We’ll be using the nano text editor, but you can also write your scripts in another terminal-based or GUI-based text editor.
1. Create a new file, hello.sh and open it with nano.
nano hello.sh
2. On the first line, specify the interpreter to use in the code. In this case, it’s Bash.The first part of the line, #!, is called the “shebang” and indicates the start of a script.
#!/bin/bash
3. On a new line use echo print a string of text on the screen.
echo “Hello World”
4. Register the code by pressing CTRL + X, then press Y and Enter.
5. Run the code from the terminal.
bash hello.sh
The output of the command is a single line of “Hello World”. This proves that our script is working and we can move on to something a bit more interesting.
Capture user input in bash scripts
Bash is a fully formed language, and with it we can create interactive tools and applications. In this example, we’ll create a greeting generator that will capture the username and then choose a random greeting from an array of greetings.
1. Create a new file, random-greetings.sh using nano.
nano random-greetings.sh
2. On the first line, specify the interpreter to use in the code. In this case, it’s Bash.
#!/bin/bash
3. Add an echo to print a message to the user.
echo "Welcome to the Tom's Hardware Greeting Generator"
4. Read the user’s keyboard input, using a prompt to ask the user a question. User input is saved in a variable name.
read -p "What is your name?: " name
5. Create a table greeting which will store five greetings. An array is a list of items stored with an index number. Using the array name and index number, we can extract elements (greetings) from the array.
greeting[0]="Hola"
greeting[1]="Greetings"
greeting[2]="How do"
greeting[3]="Hey there"
greeting[4]="Howdy"
6. Create variable Cut which will store the number of elements in the array.
size=${#greeting[@]}
7. Create variable index and store a randomly chosen number between zero and the size of the array, in this case five elements.
index=$(($RANDOM % $size))
8. Use echo to print the randomly chosen greeting with the user’s name.
echo ${greeting[$index]} $name
9. Save the code by pressing CTRL+X, then press Y and Enter.
ten. Run the code from the terminal. Follow the instructions to view the welcome message.
bash random-greetings.sh
Using arguments with bash scripts
The beauty of the terminal is that we can pass additional arguments, instructions or parameters to a command. In this example, we are going to write a bash script to check the status of a URL, passed as an argument.
1. Create a new file site-check.sh and open nano.
nano site-check.sh
2. On the first line, specify the interpreter to use in the code. In this case, it’s Bash.
#!/bin/bash
3. Using echo, write a message to the user informing them of the current HTTP response code for the URL. The value of $1 is the URL we specified as an argument.
echo "The current HTTP response for " $1 " is..."
4. Create a variable, response to store the output of the loop order. By using the -write argument, we specify that we want to see the HTTP response code. Another argument, -quiet will ensure that we don’t see all of the command’s output spilling onto the screen. We then send any residual output such as errors to /dev/null, essentially a black hole for data. Finally we use the $1 argument (our URL to check) to complete the command.
response=$(curl --write-out "%{http_code}n" --silent --output /dev/null "$1")
5. Use echo to print the HTTP response code to the terminal.
echo "${response}"
6. Save the code by pressing CTRL+X, then press Y and Enter.
7. Run the code from the terminal; remember to include a fully qualified domain name to verify.
bash site-check.sh https://tomshardware.com
Creating a system-wide executable Bash script
Currently, our scripts are working fine, but they are not available system-wide as an executable file. Let’s change that. For this last part, we will convert the site-check.sh script into an application that we can use from any location on the drive.
First we need to make the file executable, then we can copy the file to /usr/bin to create an executable available anywhere.
1. Open a terminal window and navigate to site-check.sh.
2. Use chmod to set the file as executable. The +x argument specifies that the file should be executable.
chmod +x site-check.sh
3. Run the script. By using ./ we tell the terminal to run an executable file in the current directory.
./site-check.sh https://bigl.es
4. Copy site-cehck.sh into the /usr/bin/ directory and change the target file name to remove the .sh extension. Note that we will need to use sudo like /usr/bin The directory does not belong to our user. Take a look at our user, file and folder permissions tutorial for more information.
sudo cp site-check.sh /usr/bin/site-check
5. Course site verification to test that the command works as expected. Remember to include a URL to verify.
Comments are closed.