Shell Script Basics
1. What is a Shell Script?
A shell script is a text file containing a series of commands that are
executed by a shell interpreter.
Common shell interpreters include Bash, sh, zsh, etc.
2. Creating a Shell Script
1. Open a text editor (e.g., nano, vim, or a GUI editor).
2. Write your script, starting with the shebang line:
bash
Copy code
#!/bin/bash
3. Save the file with a .sh extension (e.g., script.sh).
3. Running a Shell Script
Method 1: Directly execute it (requires execution permissions):
bash
Copy code
chmod +x script.sh # Make it executable
./script.sh # Run the script
Method 2: Run with the interpreter explicitly:
bash
Copy code
bash script.sh
Key Features and Syntax
1. Comments
Use # to add comments. Comments are ignored by the interpreter.
bash
Copy code
# This is a comment
echo "Hello, World!"
2. Variables
Assign values to variables without spaces.
bash
Copy code
name="John"
echo "Hello, $name"
Use $ to access a variable’s value.
3. Input and Output
Input: Use the read command.
bash
Copy code
echo "Enter your name:"
read name
echo "Welcome, $name!"
Output: Use the echo command.
bash
Copy code
echo "This is a message"
4. Control Structures
a. If Statements
bash
Copy code
if [ condition ]; then
# Code to execute if condition is true
else
# Code to execute if condition is false
fi
Example:
bash
Copy code
if [ "$name" == "Alice" ]; then
echo "Hello, Alice!"
else
echo "You're not Alice."
fi
b. Loops
For Loop:
bash
Copy code
for i in 1 2 3; do
echo "Number: $i"
done
While Loop:
bash
Copy code
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
5. Functions
Define reusable blocks of code:
bash
Copy code
my_function() {
echo "This is a function."
}
my_function # Call the function
6. Command Substitution
Run a command and use its output:
bash
Copy code
current_date=$(date)
echo "Current date: $current_date"
7. File Operations
Check if a file exists:
bash
Copy code
if [ -f "file.txt" ]; then
echo "File exists."
else
echo "File does not exist."
fi
Create a file:
bash
Copy code
touch newfile.txt
8. Redirection
Redirect output to a file:
bash
Copy code
echo "Hello" > output.txt # Overwrites the file
echo "World" >> output.txt # Appends to the file
Redirect input from a file:
bash
Copy code
wc -l < input.txt # Count lines in the file
Redirect errors:
bash
Copy code
ls nonexistentfile 2> error.txt # Write errors to error.txt
Useful Commands
Command Description
pwd Print the current directory
ls List files in the directory
cd Change directory
cp Copy files
mv Move/rename files
rm Remove files/directories
echo Print messages
cat Display file contents
grep Search text in files
chmod Change file permissions
date Display current date/time
Example Shell Script
bash
Copy code
#!/bin/bash
# A simple script to display system info
echo "Welcome, $(whoami)!"
echo "Current Date and Time: $(date)"
echo "Your Current Directory: $(pwd)"
echo "System Uptime: $(uptime)"