Learn How to Execute a Shell Script in Linux – This guide will cover the different ways of running shell scripts on a Linux system, including setting the proper permissions, executing scripts with different shells, and troubleshooting common issues. With this knowledge, you will be able to automate repetitive tasks and perform system maintenance with ease.

So, let’s get started.

What is Shell?

A shell also called a command-line Interpreter, is a program that accepts input from the keyboard and executes commands for you by displaying the output.

It is usually a small program that has been designed to run in an operating system. This allows users to interact with the system.

The most common operating systems with shells are Unix (which includes Linux, Mac OS x, and Solaris) and Microsoft Window.

If you are using a different operating system, there may be an equivalent built-in command line interpreter available.

What is a Shell Scripting?

Many people are familiar with the command line, but there is also a whole world of scripts that can be written to automate tasks.

Shell scripting is an extension of the command line that allows you to perform tasks more quickly and easily with the help of functions, loops, commands, and variables.

Shell Scripts are very useful when you want to perform repetitive tasks.

Let’s say you have a lot of files on your computer, it can be very time-consuming to go through them all one by one to make sure they are in order and are not corrupted or damaged in any way.

A good shell script can automate this process by running a sorting program on each file and then moving them into specific folders based on their names.

That’s fascinating!

Some of the most common uses of shell script automation include:

  • Managing files and directories
  • Deployment tasks, such as setting up a development or production environment, building and deploying code, or rolling back to previous versions
  • System maintenance tasks, such as regular backups, disk clean-ups, or log rotations
  • Data processing tasks, such as extracting, transforming, and loading data from various sources
  • Networking tasks, such as configuring and managing network devices or monitoring network traffic
  • Monitoring tasks, such as checking the status of servers or services and sending alerts when there are issues
  • Performing file operations such as copying, moving, or deleting files
  • E.t.c

How to Execute Shell Script in Linux: The Complete Guide to Running Scripts

A shell script is a program written in the shell programming language, which can be executed in a terminal window.

To run a shell script, you need to make the script file executable, and then run it using the appropriate command. The most common way to make a script file executable is by using the "chmod u+x" command, which changes the file permissions to allow execution.

Once the script is made executable, you can run it by typing "./scriptname.sh" in the terminal.

Another way to run a script is to specify the interpreter and the script name as arguments to the interpreter, such as "bash scriptname.sh" or "sh scriptname.sh"

A shell script needs to be saved with the extension .sh

Shell script begins with the shebang line #! to let the Linux system know which interpreter to use for the shell script.

For environments that support bash,

Use:

#!/bin/bash

The environment refers to the set of variables and their values that are available to a shell script when it is run

To know the name of the SHELL you are using, run the code below;

echo $SHELL

Output:

how to execute shell script in linux

This shows the type of environment we are running our script, which in our case is bash.

There are different SHELL environments one can work with, like

  • Bourne Shell (sh),
  • Bourne-Again Shell (bash),
  • C Shell (csh),
  • Korn Shell (ksh),
  • Z Shell (zsh)
  • etc.

These are the most commonly used SHELL in Linux.

Creating and Running a Basic Shell Script in Linux

To create a shell script, you can use any editor or the vi which comes in handy with the Linux operating system.

To open the vi editor,

  • Go to your terminal
  • Type vi basic_shell.sh
  • Then, press enter on the keyboard (This will open the editor)
how to execute shell script in linux

Note:

vi is the editor

basic_shell is the name given to the script (you can choose any name of your choice)

.sh is the extension

Once your vi editor is open, you will see an interface like the one below

how to execute shell script in linux

You are now inside the vi editor.

To enable the keyboard input inside the vi editor,

Press i

This activates the INSERT MODE of the editor

Now, type your scripts starting with the shebang#!/bin/bash

#!/bin/bash
whoami

cal

This script runs the commands whoami and cal.

Whoami displays the active username.

Cal displays the calendar.

To save and exit the vi editor

  • Press ESC on the keyboard
  • Type : (colon character)
  • Type wq (after the colon)
  • Press ENTER
how to execute shell script in linux

Finally, you can run the script with the following command:

bash basic_script.sh

This produces the output below:

how to execute shell script in linux

The first line of the output corresponds to the whoami command which prints the username of the current user.

While the second line which is the calender corresponds to the cal command.

You can also run a script without including the bash command by using the method below

./bash_script.sh
how to execute shell script in linux

Looking at the output, it says permission denied.

Let’s troubleshoot this issue together 👏

To run a script without the bash command requires a permission

To give permission, run the following command bellow;

chmod u+x bash_script

This command applies chmod and gives x (executable) permissions to the current user u

Great Job! 👍

Let’s run the command ./bash_script again;

how to execute shell script in linux

Congratulations on a job well done!

The command bash only requires the read permission from the file. While the command ./, runs the file as an executable and requires the execute permission

Using Variables in Shell Scripts

In a shell script, variables are used to store values that can be used later in the script.

Here is an example of how to use variables in a shell script:

Example 1:

#!/bin/bash
# This is a comment
# Declare a variable called "name" and give it the value "Roland"
NAME="Roland"
# Print a message using the value of the "name" variable
echo "Hello, $NAME!"

Output:

how to execute shell script in linux

Example 2:

#!/bin/bash
# Declare a variable called "count" and give it the value "5"
COUNT=5
# Print a message using the value of the "count" variable
echo "The count is $COUNT."
# Perform arithmetic using the "count" variable
result=$((COUNT + 3))
# Print the result of the arithmetic
echo "The result is $result."

Output:

how to execute shell script in linux

In this example, the variables “NAME” and “COUNT” are declared and given values. The script then uses the values of these variables in various ways, such as printing messages and performing arithmetic.

To use a variable in a shell script, you first declare it using the syntax “variable_name=value”.

You can then use the variable by enclosing it in a dollar sign and curly braces, like this: “${variable_name}”.

Reading Input from the command line

In a shell script, you can use the read command to read input from the command line and store it in a variable.

Here is an example of how to use the read command in a shell script:

#!/bin/bash
# Prompt the user for input
echo "Enter your name: "
# Read the user's input and store it in a variable called "name"
read NAME
# Print a greeting using the value of the "name" variable
echo "Hello, $NAME"

Output:

how to execute shell script in linux

In this example, the script prompts the user for input by printing a message using the echo command.

It then uses the read command to read the user’s input and store it in a variable called “NAME”.

Finally, it prints a greeting using the value of the “NAME” variable.

To make sure we’ve retained all the important information, let’s summarize before we wrap up.

1: Open your text editor and create a new file.

2: Define the shebang line.

3: Write your script.

4: Give your script proper execution rights.

5: Execute your script with the commands below.

Step A: For Linux scripts that reside on the server, you can run them in one of two ways:

Once you have saved your file, make sure it has been given executable permission by using the chmod command to change the file’s permissions: chmod u+x hello.sh

Step B: For scripts that live inside your user’s home directory, you can run them directly by typing their name on the terminal and adding a dot-slash (./) before it.

The dot slash (./) tells bash to execute this file in this current directory even if it is not set as an environment PATH variable.

The official Linux man page for the “bash” command provides detailed information about the command, including its usage, options, and examples.

Bash, which stands for Bourne Again Shell, is the most commonly used shell in Linux and is based on the Bourne Shell, which was the original Unix shell.

The man page is a comprehensive resource for understanding and using the bash command, and can be used as a reference for advanced users.

For more detailed information about the ‘bash’ command, including its usage and options, check out the official Linux man page at https://linux.die.net/man/1/bash.”

Congratulations 👏

You now know how to use a shell script to execute a command in Linux! With this knowledge, you can automate tasks, save time, and streamline your workflow.

But this is just the beginning. There is so much more you can do with shell scripts, from reading and manipulating data to interacting with the operating system and other programs.

With a little practice and creativity, the possibilities are endless. Don’t be afraid to experiment and try out new ideas.

The more you work with shell scripts, the more confident and proficient you will become.

So go ahead and put your new found skills to test!

Who knows what amazing things you will be able to accomplish with a shell script?

I would love to hear your thoughts on this topic. Feel free to leave a comment below and let me know what you think!