Introduction to Unix Shell Scripting
Shell scripting is a powerful tool for automating tasks in Unix-like operating systems. It allows
users to write a sequence of commands in a file and execute them as a script, saving time and
effort by avoiding repetitive command execution. Shell scripts can perform various tasks such as
file manipulation, program execution, and text printing.
Creating and Running a Bash Script
To create a bash script, follow these steps:
Create a file: Use the touch command to create a new file with a .sh extension.
touch hello_world.sh
Add the shebang: The first line of the script should be the shebang ( #! ) followed by the path
to the bash interpreter.
#! /bin/bash
Write commands: Add the commands you want to execute. For example, to print "Hello
World":
echo "Hello World"
Make the script executable: Use the chmod command to give execution rights to the script.
chmod u+x hello_world.sh
Run the script: Execute the script using one of the following commands:
./hello_world.sh
bash hello_world.sh
Basic Syntax and Operations
Variables
Variables in bash are defined using the syntax variable_name=value . To access the value
of a variable, prefix it with $ .
#!/bin/bash
greeting="Hello"
name="Tux"
echo $greeting $name
Arithmetic Expressions
Bash supports basic arithmetic operations such as addition, subtraction, multiplication, division,
exponentiation, and modulus.
#!/bin/bash
var=$((3 + 9))
echo $var
User Input
To read user input, use the read command.
#!/bin/bash
read -p "Enter your age: " age
echo "Your age is $age"
Conditional Statements
Conditional statements allow you to execute commands based on certain conditions.
#!/bin/bash
read -p "Enter a number: " x
read -p "Enter another number: " y
if [ $x -gt $y ]; then
echo "X is greater than Y"
elif [ $x -lt $y ]; then
echo "X is less than Y"
else
echo "X is equal to Y"
fi
Loops
Loops allow you to execute commands repeatedly.
#!/bin/bash
for i in {1..5}; do
echo $i
done
Reading Files
You can read a file line by line using a while loop.
#!/bin/bash
LINE=1
while read -r CURRENT_LINE; do
echo "$LINE: $CURRENT_LINE"
((LINE++))
done < "sample_file.txt"
Finding Existing Scripts
Use the find command to locate scripts in the system.
find . -type f -name "*.sh"
Shell scripting is an essential skill for automating tasks and improving productivity in Unix-like
systems. By mastering the basics of shell scripting, you can create powerful scripts to handle