Shell Script Basics
What is a Shell Script?
A shell script is a text file containing a series of commands that can be executed by a shell interpreter. In Linux systems, Bash (Bourne Again Shell) is the most commonly used shell for scripting.
Basic Structure of a Shell Script
Every shell script typically starts with a shebang line that specifies the interpreter:
#!/bin/bash
Simple Example Script
Here's a basic shell script that demonstrates fundamental concepts:
#!/bin/bash
## Variable declaration
name="LabEx User"
## Printing output
echo "Welcome to Linux Shell Scripting!"
echo "Hello, $name"
## Simple arithmetic
result=$((10 + 5))
echo "10 + 5 = $result"
Script Execution Modes
Shell scripts can be executed in different ways:
Execution Method |
Command |
Description |
Direct Execution |
./script.sh |
Requires executable permission |
Bash Interpreter |
bash script.sh |
Runs script without changing permissions |
Source Command |
source script.sh |
Executes script in current shell environment |
Permissions and Execution
To make a script executable:
chmod +x script.sh
Command Line Arguments
#!/bin/bash
## $0 is script name, $1, $2 are first and second arguments
echo "Script Name: $0"
echo "First Argument: $1"
echo "Total Arguments: $#"
#!/bin/bash
read -p "Enter your name: " username
echo "Hello, $username!"
Control Structures
Conditional Statements
#!/bin/bash
if [ $## -eq 0 ]; then
echo "No arguments provided"
elif [ $## -gt 3 ]; then
echo "Too many arguments"
else
echo "Arguments provided: $#"
fi
Loops
#!/bin/bash
## For loop
for item in apple banana cherry
do
echo "Fruit: $item"
done
## While loop
counter=0
while [ $counter -lt 3 ]
do
echo "Counter: $counter"
((counter++))
done
Best Practices for Beginners
- Always use
#!/bin/bash
at the script's beginning
- Make scripts executable with
chmod +x
- Use meaningful variable names
- Add comments to explain complex logic
- Handle potential errors gracefully
By understanding these basics, you'll be well-prepared to write robust and efficient shell scripts in your Linux environment.