The Wayback Machine - https://web.archive.org/web/20240904220926/https://www.geeksforgeeks.org/how-to-create-a-shell-script-in-linux/
Open In App

How to Create a Shell Script in linux

Last Updated : 13 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Shell is an interface of the operating system. It accepts commands from users and interprets them to the operating system. If you want to run a bunch of commands together, you can do so by creating a shell script. Shell scripts are very useful if you need to do a task routinely, like taking a backup. You can list those commands and execute them all with just a single script. Let’s see how you can create a shell script and run it on Linux.

Creating a Shell Script

Login to your Linux machine and open the terminal, navigate to the folder where you want to store the shell script. Shell scripts end with the extension “.sh”. Let’s create our first shell script. Type in

touch script.sh

Now, this script file is not executable by default, we have to give the executable permission to this file. Type in

chmod +x script.sh

Now, we will add some commands to this shell script. Open this shell script with any text editor of your choice (command-line based or GUI based) and add some commands. We will use nano. Type in 

nano script.sh

Add the following commands to test this shell script

echo This is my first shell script
touch testfile
ls
echo End of my shell script

Save the changes, and run the shell script by typing in

./script.sh

Screenshot of above steps

You can see, it executed all the specified commands.

Comments in the shell script

Any line which starts with “#” in the shell script is treated as a comment and is ignored by the shell during execution, except the shebang line, which we will see later in this article. Let’s see an example. A shell script is created with the following content.

# This is a comment
echo Testing comments in shell script

Comments in Shell Script

You can see, the comment gets ignored.

Variables in Shell Script

Yes, Shell scripts support the use of variables, and we need not define a variable’s type during its declaration. There are two types of variables:

  • System Defined variables
  • User-Defined Variables.

System-defined variables, also called environment variables, are generally Capitalised. You can view all the current environment variables using the printenv command. User-Defined variables are set by the user, and they exist only during script execution. You can define a variable by simply typing its name and assigning a value with = sign and access a variable by adding a $ before the variable name. Variables are demonstrated in the following example script.

# Accessing an Environment Variable
echo $USER

# Creating and accessing User defined Variable
variable_name="Geeksforgeeks"
echo $variable_name

Variables in Shell Script

Defining the Shell Script interpreter

There are many Shells available in Linux, such as The bourne shell(sh), The Korn Shell(ksh), and GNU Bourne-Again Shell(bash). Scripts written for the sh shell are called shell scripts, and they can be interpreted by both, the ksh and bash shells. ksh and Bash are improved versions of the original sh shell and they have more features than sh. Bash is generally the default shell in most of the Linux Distributions and scripts written specifically for bash shell are called bash scripts. 

You can specify which shell the script will use, even if the script is executed from another shell terminal. To do this, add “#!” on top of the script file, followed by the absolute path of the shell of choice. To specify bash as an interpreter, Add the following line on top of the shell script.

#!/bin/bash

This line is called the shebang line.

Note: This will only work if bash is installed on your system. 

Comparison Operators

You can compare two variables in shell scripting. We do these comparisons to make decisions, we will see how to do that later in this article, but before that, here is a list of some comparison operators.

Integer comparison

Operator Description
-eq is equal to
-ne is not equal to
-gt is greater than
-ge is greater than or equal to
-lt is less than
-le is less than or equal to

String Comparison

Operator Description
== is equal to
!= is not equal to
\< is less than, in ASCII alphabetical order
\> is greater than, in ASCII alphabetical order

We add a \ before < and > because they need to be escaped when typed in the [ ] construct. Now, let’s see where these are used.

Conditional statements

Conditional statements are used to execute a block of code only when certain conditions are met. Shell scripts support the use of conditional statements. We use comparison operators to check the conditions. Let’s see a few conditional statements.

If statement

It checks the condition, and if it is conditioned true, it executes the commands. 

Syntax

if [ condition ]
then
#statements
fi

Let’s see an example.

#!/bin/sh
x=10
y=11
if [ $x -ne $y ] 
then
echo "Not equal"
fi

.if statement

If-else statement

In an if-else statement, you can specify a set of commands to run if the condition is not met.

Syntax

if [ condition ]
then
#set of statements if the condition is true
else
#set of statements if the condition is false
fi

Let’s see an example

#!/Syntaxbin/sh
x=10
y=10
if [ $x -ne $y ] 
then
echo "Not equal"
else
echo "They are equal"
fi

.if-else statement

There are other conditional statements, you can read about them here.

Note: Type a space after [ and before ] while specifying the condition to be checked otherwise you will get an error.

Loops

Using loops, you can a set of commands over and over again, until a certain condition is met. Let’s see some of the loops.

While loop

It starts running the specified commands if the condition is true and repeats them until the condition is false.

Syntax

while [ condition ]
do
#set of statements
done

Let’s see an example.

#!/bin/sh
x=2
while [ $x -lt 6 ]
do
echo $x
x=`expr $x + 1`
done

While loop

We enclose an expr statement within ` ` when assigning it to a variable. You can read about expr command here.

For loop

In a for loop, the variable iterates over a list of values and ends when there are no more values to iterate over.

Syntax

for var in val1 val2 val3
do
#statements
done

Let’s see an example.

#!/bin/sh
for var in 2 4 5 8
do
echo $var
done

for loop

You can read about loops in detail here.

Positional Arguments

Positional arguments are the arguments or values which we pass to the shell script while executing the script. They are accessed by variables $0, $1, $2 … $9. Beyond that, they are referenced by ${10}, ${11} and so on. $# stores the no of passed arguments and $0 stores the name of the script. Let’s see an example to understand all this.

#!/bin/sh
echo "No of arguments is $#"
echo "Name of the script is $0"
echo "First argument is $1"
echo "Second argument is $2"

To pass the arguments, just type them in the terminal after the script name as shown below.

Positional Arguments

Storing the output of commands

You can store the output of commands inside a variable in a shell script. There are two ways to do so.

Syntax

#Syntax 1
var=$(a valid linux command)
#Syntax 2
var2=`a valid linux command`

Let’s see an example.

#!/bin/sh
b=$(pwd)
c=`pwd`
echo $b
echo $c
d=$(ls /bin | grep bash)
echo $d

Storing the output of commands

Exit Codes of shell commands

Whenever a command ends and returns the control to the parent process, it returns exit codes between 0 and 255. Exit code 0 means the command was successful, and any other exit code means, the command was unsuccessful. You can view the exit code after running any command by accessing the $? variable. See the example below.

exit code of shell command

You can manually set an exit code for your shell script. This can be used with conditional statements to convey if the script’s purpose was achieved or not. 

Example

#!/bin/sh
read x
if [ $x -ne 10 ]
then
echo failed
exit 1
else
echo passed
exit 0
fi

exit code of shell command



Previous Article
Next Article

Similar Reads

Shell Script to Show the Difference Between echo “$SHELL” and echo ‘$SHELL’
In shell scripting and Linux, the echo command is used to display text on the terminal or console. When used with the $SHELL variable, which contains the path of the current user's shell program, the output of the echo command can be different depending on whether the variable is enclosed in single or double quotes. echo "$SHELL" will expand the $S
4 min read
Bash Script - Difference between Bash Script and Shell Script
In computer programming, a script is defined as a sequence of instructions that is executed by another program. A shell is a command-line interpreter of Linux which provides an interface between the user and the kernel system and executes a sequence of instructions called commands. A shell is capable of running a script. A script that is passed to
3 min read
Shell Scripting - Difference between Korn Shell and Bash shell
Korn Shell: Korn Shell or KSH was developed by a person named David Korn, which attempts to integrate the features of other shells like C shell, Bourne Shell, etc. Korn Shell allows developers to generate and create new shell commands whenever it is required. Korn shell was developed a long year back as it is older than the BASH shell and it has fe
3 min read
Shell Script to Demonstrate the Use of Shell Function Library
Shell Function Library is basically a collection of functions that can be accessed from anywhere in the development environment. It actually makes shell scripting a bit less tedious and repetitive. By creating a shell script with some functions defined in it, we can then access and call those functions from other files or scripts. It helps in avoid
3 min read
How to write a shell script that starts tmux session, and then runs a ruby script
Scripts are important for streamlining workflows and automating tasks. One such way to streamline workflow is by using Tmux [Terminal Multiplexer]. When used along with shell scripts we will be able to automatically commence a Tmux session and perform certain tasks. In this article, we shall see how to use a shell script that will automatically sta
4 min read
Create multiple users using shell script in Linux
In Linux, we create users for multiple purposes, so in Linux, it's very common to make new users depending on the tasks. So sometimes we need to create more than one user or multiple users. We can't do it one by one as it would be very time-consuming, so we can use automated scripts to make our tasks easy. Here we have used a shell script to make m
3 min read
Auto Logout in Linux Shell Using TMOUT Shell Variable
TMOUT is a Linux-Unix shell variable that provides the user security for their login session in the system. It provides the "Auto Logout Functionality" for the login shell in case of no activity for a specified time. Generally when the user leaves the Linux system idle (situation when a user doesn't perform any administrative task by running a comm
2 min read
How to protect Linux shell file using noclobber in bash shell?
Most Linux shells(bash, csh, ksh, tcsh) have a built-in file protection mechanism to prevent files from being overwritten accidentally. In this article, we will see how to prevent it by setting noclobber option. Clobbering Redirecting standard output to a file that already exists would overwrite the existing file content which will result in data l
2 min read
Introduction to Linux Shell and Shell Scripting
If we are using any major operating system, we are indirectly interacting with the shell. While running Ubuntu, Linux Mint, or any other Linux distribution, we are interacting with the shell by using the terminal. In this article we will discuss Linux shells and shell scripting so before understanding shell scripting we have to get familiar with th
7 min read
Difference Between Single and Double Quotes in Shell Script and Linux
Single quotes and double quotes are both functional in Linux while working with shell scripts or executing commands directly in the terminal but there is a difference between the way the bash shell interprets them. Single quotes: Enclosing characters in single quotation marks (') holds onto the literal value of each character within the quotes. In
3 min read
Shell Script to Demonstrate Wait Command in Linux
Wait command is one of the process management commands. There are different process commands in Linux mainly 5 commands are widely used which are ps, wait, sleep, kill, exit. ps is an acronym for process status. It displays information about the active processes. wait command will suspend execution of the calling thread until one of its children te
4 min read
How to Enable Shell Script Debugging Mode in Linux?
Linux is a very popular operating system especially among developers and in the computer science world, as it comes along with its powerful ability to play with the kernel. Major Linux distributions (often referred to as Linux distros) are Open Source (Source Code available and can be modified on request) in nature like Ubuntu, CentOS, etc. Bash is
5 min read
Shell Script to Scrape prices of Cryptocurrency coins in Linux
Cryptocurrency is such a hype that everyone wants to be a part of it. Even nerds and programmers want to dive into this amazing field because it is quite versatile and interesting in every aspect. So how about scraping the price of cryptocurrency coins such as bitcoin, ethereum, dogecoin, and a ton of other coins using shell script and coingecko.co
8 min read
Shell Script to Automate System Updates and Upgrades in Linux
Shell Scripts are often used for automating repetitive tasks that we can perform on a daily basis. With shell scripts, you can automate tasks like renaming a bunch of files or making backup scripts and many more complex tasks. As we all know, we often need to update and upgrade Linux packages and delete the older version and unnecessary files and g
4 min read
How to prompt for Yes/No/Cancel input in a Linux shell script
You may have noticed that shell programs occasionally ask the user for confirmation by prompting [Y/n] or [Yes/No]. Knowing whether a user wishes to continue with the following stages or not is useful. A similar feature can be added to your script as well. This article will assist you with examples of this sort of input (Bash Script - Prompt to Con
3 min read
Linux Shell Script to Sync Directories Interactively
Scripts that sync directories are scripts used to synchronize the contents of two directories. This means that the script will ensure that the two directories have duplicate files and directories and that the contents of the files are the same. There are various ways to sync directories, and the specific approach depends on the requirements of the
7 min read
How to display nc return value in Linux shell script?
When you need to monitor network connections and understand their status, creating a custom bash script can be an invaluable solution. This article demonstrates how to build a bash script that checks network connections using the nc command and displays the corresponding exit status. By providing a user-friendly menu-driven interface, this script e
6 min read
Linux Shell Script to Backup Files and Directory
Backing up our important files and directories is crucial to safeguarding our data. In this article, we’ll create a simple shell script that uses the tar utility to create an archive file for backup purposes that we can use whenever we require. The shell script we’ll build allows us to specify which directories to back up and where to store the bac
5 min read
Shell Script to create a compressed archive of the specified directory
An archive is a simple process of storing a group of files or folders into one file. Sometimes we may need to create a compressed archive out of a single folder so that we can share it with others or for something else. In Linux, to ease the task, we can create a shell script to automate the process of creating an archive by simply providing the fo
3 min read
Shell Scripting - Restricted Shell
Shell is one of the most important and powerful tools available in GNU/Linux-based systems. One can control the entire system if used correctly, this exact feature makes the shell a double-edged sword. It can potentially harm the system if one executes a system command without knowing its underlying details and consequences. To prevent this we use
5 min read
Shell Scripting - Interactive and Non-Interactive Shell
A shell gives us an interface to the Unix system. While using an operating system, we indirectly interact with the shell. On Linux distribution systems, each time we use a terminal, we interact with the shell. The job of the shell is to interpret or analyze the Unix commands given by users. A shell accepts commands from the user and transforms them
3 min read
Shell Scripting - Default Shell Variable Value
A shell gives us an interface to the Unix system. While using an operating system, we indirectly interact with the shell. On Linux distribution systems, each time we use a terminal, we interact with the shell. The job of the shell is to interpret or analyze the Unix commands given by users. A shell accepts commands from the user and transforms them
3 min read
Korn Shell vs Bash Shell
Introduction : Korn Shell, also known as ksh, is a Unix shell that was developed by David Korn in the early 1980s. It was designed to be a more powerful and interactive shell than the Bourne Shell (sh), which was the standard Unix shell at the time. The Korn Shell has features such as command-line editing, job control, and shell scripting, making i
6 min read
Shell Scripting - Shell Signals Values
Prerequisites: Processes, Bash Scripting, Shell Function Library Signals help the operating system to communicate with processes and vice-versa. Signals are also generated when processes don't function properly or try to access prohibited memory. Different signals are mapped to different numbers which are referred to as signal values. The Linux OS
6 min read
Shell Scripting - Shell Variables
A shell variable is a character string in a shell that stores some value. It could be an integer, filename, string, or some shell command itself. Basically, it is a pointer to the actual data stored in memory. We have a few rules that have to be followed while writing variables in the script (which will be discussed in the article). Overall knowing
6 min read
Bash shell script to find sum of digits
Given a number Num, find the sum of digits of the number.Examples: Input : 444 Output : sum of digits of 444 is : 12 Input : 34 Output : sum of digits of 34 is : 7 Approach: 1. Divide the number into single digits 2. Find the sum of digits . C/C++ Code # !/bin/bash # Program to find sum # of digits # Static input of the # number Num=123 g=$Num # st
1 min read
Conditional Statements | Shell Script
Conditional Statements: There are total 5 conditional statements which can be used in bash programming if statement if-else statement if..elif..else..fi statement (Else If ladder) if..then..else..if..then..fi..fi..(Nested if) switch statement Their description with syntax is as follows: if statement This block will process if specified condition is
3 min read
String Operators | Shell Script
Pre-Requisite: Conditional Statement in Shell Script There are many operators in Shell Script some of them are discussed based on string. Equal operator (=): This operator is used to check whether two strings are equal. Syntax:Operands1 = Operand2Example: PHP Code #!/bin/sh str1=&amp;quot;GeeksforGeeks&amp;quot;; str2=&amp;quot;geeks&amp;quot;; if
2 min read
Implementing Directory Management using Shell Script
Directory management constitutes the functions dealing with organization and maintenance of various directories. Directories usually contain files of any type, but this may vary between file systems. The content of a directory does not affect the directory object itself. Some of the directory functions are: Navigation Absolute/ Relative Pathnames L
3 min read
Bash shell script to find out the largest value from given command line arguments
Write a shell script to find out the largest value from the given number of command-line arguments. Example: Special variables in bash: $@- All arguments. $#- Number of arguments. $0- Filename. $1, $2, $3, $4 ... - Specific arguments. Approach If the number of arguments is 0, end the program. If not zero, then Initialize a variable maxEle with firs
1 min read