Shell Script Basics
Shell Script Basics
Shell Script Basics
bash
Copy code
#!/bin/bash
bash
Copy code
chmod +x script.sh # Make it executable
./script.sh # Run the script
bash
Copy code
bash script.sh
1. Comments
bash
Copy code
# This is a comment
echo "Hello, World!"
2. Variables
bash
Copy code
echo "Enter your name:"
read name
echo "Welcome, $name!"
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
bash
Copy code
my_function() {
echo "This is a function."
}
6. Command Substitution
bash
Copy code
current_date=$(date)
echo "Current date: $current_date"
7. File Operations
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
bash
Copy code
echo "Hello" > output.txt # Overwrites the file
echo "World" >> output.txt # Appends to the 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