Introduction to Bash Scripting
Bash (Bourne Again SHell) is a Unix shell and command language that is widely used for scripting and automating tasks on Linux and Unix-like systems. It's powerful, flexible, and an essential skill for system administrators and developers.
What is Bash?
Bash is a command processor that typically runs in a text window where the user types commands that cause actions. It can also read and execute commands from files, called shell scripts.
Why Learn Bash?
- Automation: Automate repetitive tasks
- System Administration: Manage servers and systems
- Portability: Works across most Unix-like systems
- Power: Combine simple commands to perform complex operations
Your First Bash Script
#!/bin/bash
# This is a simple bash script
echo "Hello, World!"
How to Run It:
Script Components
Shebang (#!)
The first line #!/bin/bash
is called a shebang. It tells the system which interpreter
to use to execute the script.
Comments
Lines starting with #
(except the shebang) are comments and are ignored by the interpreter.
echo Command
echo
is used to output text to the terminal.
Basic Bash Commands
File Operations
# List files
ls
# Change directory
cd /path/to/directory
# Create directory
mkdir new_directory
# Copy files
cp source.txt destination.txt
# Move/rename files
mv oldname.txt newname.txt
# Remove files
rm file.txt
Text Processing
# View file content
cat file.txt
# Page through file content
less file.txt
# Search in files
grep "pattern" file.txt
# Count lines, words, characters
wc file.txt
System Information
# Show current user
whoami
# Show system information
uname -a
# Show disk usage
df -h
# Show memory usage
free -h
Script Execution Methods
1. Make Executable and Run
2. Pass to Bash Interpreter
3. Source the Script
Best Practices
- Always start with a shebang
- Use comments to explain complex logic
- Indent your code for readability
- Use meaningful variable names
- Include error handling
- Test scripts thoroughly
Debugging Bash Scripts
You can debug bash scripts by running them with the -x
option:
This will print each command before it's executed.
Next Steps
Continue learning with:
- Variables & Parameters - Learn about variables in Bash
- Control Flow - Understand conditionals and loops