Bash (Bourne Again Shell) is a popular Unix and Linux command-line interpreter and scripting language. Shell scripting in Bash refers to the process of writing scripts using the Bash shell, which enables users to create scripts that run a series of commands, control flow, and carry out complex tasks. It also provides a flexible and powerful environment for automating tasks and performing complex operations efficiently on Unix and Linux systems. In this article, you can find some basic shell script examples that will give you a good insight into basic shell scripting as a beginner.
Download Basic Shell Script Examples
Getting Started With Shell Script
Shell scripting is the process of writing a series of commands, control structures, and variables in a script file that the shell can execute line by line. To get started with shell scripting, you first have to learn how to write a bash script and make it executable. In this article, you will learn how to write bash scripts, how to make those scripts executable, and how to run them. So let’s get started.
What is SheBang (#!) in Shell Scripting?
While writing a bash script, you must start with a line that is called SheBang(#!). It specifies the interpreter or shell that should be used to run the script. The shebang line starts with a hash symbol (#) and ends with an exclamation mark (!). The path to the interpreter executable is provided immediately after the exclamation mark. So, in shell scripting, the syntax would be #!/bin/bash. However, the path specified after the exclamation mark may differ depending on the interpreter’s location on the system.
The shebang line is required because it allows scripts to be executed directly from the command line by invoking the script file rather than explicitly specifying the interpreter each time. It ensures that the script is run with the appropriate interpreter, allowing the script’s commands and logic to be executed.
How to Write and Execute a Bash Script in Linux
Here, I will demonstrate how to write a shell script and then how to execute and run it. I will create a script that will print Hello World to the users after running it. I will be using the user’s private “bin” folder since the “bin” directory can automatically be added to the $PATH variable. For editing the script, I will use the “nano” text editor. Now, follow the steps below to write the script in Linux.
Step 1: Creating a Shell Script
To create and write the shell script follow the steps below:
- First, Launch an Ubuntu Terminal using the shortcut keys CTRL+ALT+T.
- Then, create a bin folder in your home directory by typing the following command.
mkdir bin
EXPLANATION- mkdir: Creates a Directory.
- bin: User’s private bin directory.
NOTE: You can skip this step if the directory has already been created. - Then create a file with an extension .sh using the nano command and open the script in a text editor like the following.
nano hello_world.sh
EXPLANATION- nano: Opens and creates a file in nano text editor.
- hello_world.sh: File for writing the bash script
-
Now, write the following script in hello_world.sh file.
#!/bin/bash echo "Hello World"
-
To save and exit the text editor press CTRL+ O and CTRL+X .
-
Now, type the following to make the script executable for the current user in your system.
chmod +x hello_world.sh
EXPLANATION- chmod: Changes the permission of files and directories.
- +x: Argument with chmod command to add the executable permission.
- hello.sh: the bash script file.
-
Finally, restart your system to add the newly created bin directory to the $PATH variable by typing the command below.
reboot
Restarting the system by default runs the .profile script which adds the user’s private bin directory to $PATH and makes the files inside the bin directory accessible for every shell session.
Step 2: Running the Script
After restarting your system, you will be able to run the “hello.sh” script from any path under the current user account. Follow the steps below:
- Open the Terminal using CTRL+ALT+T.
- In the command line type the following command.
bash hello_world.sh
In the above image, you can see that, I successfully ran the created “hello_world.sh” script. The “Hello World” message is displayed on the terminal from that script.
Basic Shell Scripts
Bash, like any other programming language, adheres to a set of rules and syntaxes. It is essential to begin a bash script with the shebang line (#!). This line instructs the system which interpreter to use when running the script. Following the shebang, you specify the path to the bash executable program, which is typically found at /bin/bash.
In addition to becoming acquainted with Linux commands, it is important to learn other fundamental aspects of shell scripting. These are divided into three categories, including variables, operators, and conditionals.
Variables in Shell Scripting
Variables are containers that hold important information in shell scripting. They serve as system memory locations capable of storing characters, numeric values, or alphanumeric values. By referencing the variable names, these values can be accessed and manipulated. In shell scripting, the variable name is combined with a dollar sign ($), such as $VARIABLE_NAME.
The syntax for Variables in Shell Scripting is given below:
VARIABLE_NAME=VALUE
In Bash Script, declare a variable by assigning(=) value to its reference. Furthermore, print the assigned values using echo $(VARIABLE_NAME). Code > Output > You can take user input with the read command and store it in a variable. Next, use echo $(VARIABLE_NAME) to print the user input. Code > Output > The read command used with option -p allows you to prompt a message along with taking user input. You can use echo $(VARIABLE_NAME) to display the user input on the screen. Code > Output > You can concatenate multiple variables and store it into a single variable by enclosing them with a double quotation (“ ”). Code > Output > For passing values as command line arguments, you have to run the script along the values in a sequence. Later access these values using the $ and input sequence number. Code > Syntax to run the script > Output > You can store an Environment Variable in a regular manner and print it using ${!..} syntax. Code > Output > Shell scripting provides a wide range of operators to help with a variety of tasks. These operators can be chosen based on your script’s output requirements and variables. To make things easier, I’ve divided the operators in Bash Scripting into five categories. This classification will help you better understand and apply the operators. Run an addition operation using the “+” operator between defined variables. Code > Output > Subtract two numbers using the “–” operator between defined variables. Code > Output > Run a division using the “/” operator between defined variables. Code > Output > For generating the remainder of a division use the “%” operator between defined variables. Code > Output > Utilize the RANDOM function of bash for generating random numbers in a range. Code > Output > Generate random numbers of specified numbers by calculating range and with the RANDOM function. Code > Output > Perform multiple operations using echo without storing the results into another variable. Code > Output > The given script performs either of the bitwise AND, OR, or NOT operations on the 2 input numbers. If the user enters any other operand as input, then the script displays an error message. Code > Output > Conditional statements are essential for automating tasks with shell scripting. These statements allow specific codes to be executed based on the fulfillment of certain conditions. A basic conditional statement in programming languages evaluates a condition and executes the associated code block if the condition is met. There are four types of conditional statements in Bash Scripting. To learn more about the syntax of conditional statements follow the table given below. #code to execute fi #code to execute else #code to execute fi #code to execute elif [ condition2 ]; then #code to execute else #code to execute fi pattern1) #code to execute;; pattern2) #code to execute;; *) #code to execute if expression doesn’t match any patterns;; esac Check odd and even numbers with simple if-else conditions. Code > Output > To perform user input-based operations implement the if-elif-else condition. Code > Output > You can perform user input-based operations with the case statement as well. Code > Output > A valid email can be checked by defining the email syntax inside the if condition. Code > Output > To check a valid URL use a simple if-else condition with the URL pattern inside the condition. Code > Output > Check if a given number is positive or negative with comparison operators inside the if-elif-else condition. Code > Output > You can verify file permissions inside the if-else condition. For this, the write permission is checked with the -w notation. Code > Output > Check a file’s existence in the current directory using the -f notation. Code > Output > Check a directory’s existence in the current folder using the -d notation. Code > Output > Besides learning the categorized shell scripts example, the following basic scripts will give you a hands-on experience in bash scripting. Modify the usage of the echo command with -e and \n to print messages in a new line. Code > Output > You can modify the default Internal Field Separator of bash by accessing the IFS variable. By changing the IFS you will be able to access values separated by your desired delimiter. After this task again restore the original IFS to avoid any error. Code > Output > You can do direct mathematical operations on command line arguments using the $((..)). Code > Syntax to run the script > Output > In bash, you can utilize the read command for taking password type inputs. The application of read with -sp option hides the input characters when you type them. Code > Output > You can take timed input in bash using the read command with -t option. The prompt message will disappear if you do not complete entering your values within the specified time. Code > Output > Finally, in this article, I have tried to provide some simple shell script examples to familiarise you with the power and flexibility of shell scripting. You can now customize and automate any system based on specific needs after learning the basics of shell scripting. Although this article has only scratched the surface of shell scripting, this solid foundation will make you well-prepared to explore the vast world of shell scripting and give you the ability to master it in less time. Shell scripting refers to the creation and execution of a sequence of commands written in a shell language, such as Bash (Bourne Again SHell) in Unix-like operating systems. Shell scripts automate tasks and streamline repetitive operations by executing a series of commands in a specific order. Here’s a simple example of a Bash shell script: Here, The first line, The term “shell” in the context of operating systems refers to a command-line interpreter or interface allowing users to interact with the system. The scripting languages associated with shells, such as Bash in Unix-like systems, provide a means to automate tasks and execute commands in a sequence. Each shell, like Bash, has its scripting language tailored for creating shell scripts. These scripts use a syntax specific to the shell environment, enabling users to perform a variety of operations, automate tasks, and streamline command-line interactions. Additionally, other shells, including sh, ksh, and zsh, also have their scripting languages. To run a shell script in the terminal, first, create your script and save it with a .sh extension. Make it executable using
Example 1: Defining Variables in a Bash Script
#!/bin/bash
# Declaration of variables
name=Tom
age=12
# Displaying variables
echo $name $age
Tom 12
Example 2: Reading, Storing, and Displaying User Input using Bash Script
#!/bin/bash
echo "Enter a number:"
read num
echo "The number is: $num"
Enter a number:
12
The number is: 12
Example 3: Reading User Input With Prompt Message Using Bash Script
#!/bin/bash
read -p "Enter a number:" num
echo "The number is: $num"
Enter a number: 12
The number is: 12
Example 4: Concatenating Multiple Variables
#!/bin/bash
# Declaration of variables
name='My name is Tom.'
age='My age is 12.'
# Concatenation
info="${name} ${age}"
echo "Result: $info"
Result: My name is Tom. My age is 12.
Example 5: Passing Values to Variables as Command Line Arguments
#!/bin/bash
name=$1
age=$2
echo "My name is $name. My age is $age."
bash bin/var_example5.sh Tom 12
My name is Tom. My age is 12.
Example 6: Printing Environment Variable Using Bash Script
#!/bin/bash
read -p "Enter an Environment Variable name:" var
echo "Environment:${!var}"
Enter an Environment Variable name:
HOME
Environment:/home/anonnya
Operators in Shell Scripting
Arithmetic Operators
Numeric Operators
Logical Operators
Bitwise Operators
+ (Addition)
-lt (Less than)
&& Or, -a (AND)
& (AND)
– (Subtraction)
-gt (Greater than)
|| Or, -o (OR)
| (OR)
* (Multiplication)
-eq (Equal)
! (NOT)
! (NOT)
/ (Division)
-ne (Not equal)
^ (XOR)
% (Modulous)
-le (Less or equal)
<< (Left shift)
++ (Increment)
-ge (Greater or equal)
>> (Right shift)
– – (Decrement)
Example 1: Adding Two Numbers Using Bash Script
#!/bin/bash
num1=10
num2=20
sum=$(($num1+$num2))
echo "The Sum is: $sum"
The Sum is: 30
Example 2: Subtracting Two Numbers Using Bash Script
#!/bin/bash
num1=30
num2=20
dif=$(($num1-$num2))
echo "The difference is: $dif"
The difference is: 10
Example 3: Division of Two Numbers Using Bash Script
#!/bin/bash
num1=30
num2=5
div=$(($num1/$num2))
echo "The division is: $div
The division is: 6
Example 4: Calculating the Remainder of a Division Using Bash Script
#!/bin/bash
num1=30
num2=20
mod=$(($num1%$num2))
echo "The remainder is: $mod"
The remainder is: 10
Example 5: Generating a Random Number Between 1 and 50 Using Bash Script
#!/bin/bash
echo $((1 + RANDOM % 50))
27
Example 6: Generating a Random Number between Two Given Numbers
#!/bin/bash
read -p "Enter minimum range:" min
read -p "Enter maximum range:" max
r_num=$(( $RANDOM % ($max - $min + 1) + $min ))
echo "Random Number: $r_num"
Enter minimum range:10
Enter maximum range:35
Random Number: 24
Example 7: Performing Multiple Mathematical Operations in a Script
#!/bin/bash
read -p "Enter a number:" num1
read -p "Enter a smaller number:" num2
echo "Addition: $(($num1 + $num2))"
echo "Subtraction: $(($num1 - $num2))"
echo "Multiplication: $(($num1 * $num2))"
echo "Division: $(($num1 / $num2))"
Enter a number:35
Enter a smaller number:15
Addition: 50
Subtraction: 20
Multiplication: 525
Division: 2
Example 8: Performing a Bitwise Operation Based on User Input
#!/bin/bash
read -p "Enter two numbers: " num1 num2
read -p "Enter operation to perform (AND, OR, NOT): " op
case $op in
AND) echo "Result: $num1 & $num2 = $((num1&num2))";;
OR) echo "Result: $num1 | $num2 = $((num1|num2))";;
NOT) echo "Result: $num1 ^ $num2 = $((num1^num2))";;
*) echo "Invalid operator.";;
esac
Enter two numbers: 4 5
Enter operation to perform (AND, OR, NOT): AND
Result: 4 & 5 = 4
Conditionals in Shell Scripting
The Syntax for Conditional Statements in Shell Scripting
if
if-else
if-elif-else
case
if [ condition ]; then
if [ condition ]; then
if [ condition1 ]; then
case expression in
Example 1: Checking if a Number is an Even or Odd
#!/bin/bash
read -p "Enter a number:" num
if [ $((num%2)) == 0 ]
then
echo "The number is even"
else
echo "The number is odd"
fi
Enter a number:25
The number is odd
Example 2: Performing an Arithmetic Operation Based on User Input
#!/bin/bash
read -p "Enter a number:" num1
read -p "Enter a smaller number:" num2
read -p "Enter an operand:" op
if [ $op == + ]
then
echo "$num1 + $num2 = $((num1+num2))"
elif [ $o == - ]
then
echo "$num1 - $num2 = $((num1-num2))"
elif [ $op == * ]
then
echo "$num1 * $num2 = $((num1*num2))"
elif [ $op == / ]
then
echo "$num1 / $num2 = $((num1/num2))”
else
echo "Operator not listed"
fi
Enter a number:34
Enter a smaller number:14
Enter an operand:+
34 + 14 = 48
Example 3: Performing a Logical Operation Based on User Input
#!/bin/bash
read -p "Enter two values: " val1 val2
read -p "Enter an operation(and/or/not) to perform:" op
case $op in
and)
if [[ $val1 == true && $val2 == true ]]
then
echo "Result: true"
else
echo "Result: false"
fi;;
or)
if [[ $val1 == true || $val2 == true ]]
then
echo "Result: true"
else
echo "Result: false"
fi;;
not)
if [[ $val1 == true ]]
then
echo "Result: false"
else
echo "Result: true"
fi;;
*) echo "Invalid operator."
esac
Enter two values: true false
Enter an operation(and/or/not) to perform:or
Result: true
Example 5: Checking if a Given Input is a Valid Email ID
#!/bin/bash
read -p "Enter an email ID: " id
if [[ $id =~ ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]
then
echo "This is a valid email ID!"
else
echo "This is not a valid email ID!"
fi
Enter an email ID: [email protected]
This is a valid email ID!
Example 6: Check if a Given Input is a Valid URL
#!/bin/bash
read -p "Enter a URL: " url
if [[ $url =~ ^(http|https)://[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$ ]]
then
echo " This is a valid URL!"
else
echo "This is not a valid URL!"
fi
Enter a URL: abcdefg1234
This is not a valid URL!
Example 7: Checking if a Given Number is Positive or Negative
#!/bin/bash
read -p "Enter a number:" num
if [ $num -gt 0 ]
then
echo "The number is Positive!"
elif [ $num -lt 0 ]
then
echo "The number is Negative!"
else
echo "The number is Zero!!"
fi
Enter a number:12
The number is Positive!
Example 8: Checking if a File is Writable
#!/bin/bash
read -p "Enter a File Name:" fname
if [ -w $fname ]
then
echo "The File $fname is writable."
else
echo "The File $fname is not writable."
fi
Enter a File Name:file1.txt
The File file1.txt is writable.
Example 9: Checking if a File Exists or Not
#!/bin/bash
read -p "Enter a File Name:" fname
if [ ! -f $fname ]
then
echo "The File $fname does not exist!"
exit 1
fi
echo "The File $fname exists."
Enter a File Name:myfile.txt
The File myfile.txt does not exist!
Example 10: Checking if a Directory Exists or Not
#!/bin/bash
read -p "Enter a File Name: " dir
if [ ! -d $dir ]
then
echo "The directory $dir does not exist!"
exit 1
fi
echo "The directory $dir exists."
Enter a File Name: bin
The directory bin exists.
Miscellaneous Bash Scripts
Example 1: Echo With New Line
#!/bin/bash
echo -e 'Hi\nthere!'
Hi
there!
Example 2: Change Internal Field Separator(IFS)/Delimiter
#!/bin/bash
#store default IFS
old_IFS= $IFS
IFS=,
read val1 val2 val3 <<< "5,60,70"
echo 1st value: $val1
echo 2nd value: $val2
echo 3rd value: $val3
#restore default IFS
IFS= $old_IFS;
1st value: 5
2nd value: 60
3rd value: 70
Example 3: Take Two Command Line Arguments and Calculate Their Sum
#!/bin/bash
sum=$(( $1 + $2 ))
echo "The sum of $1 and $2 is $sum"
bash hello_world.sh 20 30
The sum of 20 and 30 is 50
Example 4: Take Password Input
#!/bin/bash
read -sp "Enter your password: " pass
echo -e "\nYour password is: $pass"
Enter your password:
Your password is: linuxsimply
Example 5: Take Timed Input
#!/bin/bash
read -t 5 -p "Enter your name within 5 seconds: " name
Enter your name within 5 seconds: Anonnya
Conclusion
People Also Ask
What is shell scripting with example?
#!/bin/bash
# This is a simple Bash script
# It prints a greeting message
echo "Hello, World!"
#!/bin/bash
, is the shebang, indicating that the Bash shell should be used to interpret the script. Following that are comments denoted by #
, providing a brief description of the script’s purpose. The core command, echo "Hello, World!"
, prints the greeting message “Hello, World!” to the terminal.What language is shell?
How to run a shell script in terminal?
chmod +x script.sh
. Then, run it using ./script.sh
in the same directory or provide the full/relative path if it’s elsewhere. Ensure the shebang line (#!/bin/bash
) is at the script’s beginning. This allows you to automate tasks and execute commands by running your script in the terminal.
FUNDAMENTALS
A Complete Guide for Beginners