Complete Bash Scripting Guide
1. Introduction to Bash
Bash (Bourne Again SHell) is a Unix shell and command language. It is widely available on various operating systems
and is a default command interpreter on most GNU/Linux systems.
Complete Bash Scripting Guide
2. Basic Syntax
- Scripts start with a shebang (#!) line: #!/bin/bash
- Comments begin with #: # This is a comment
- Commands are executed line by line.
- Semicolons (;) can separate commands on the same line.
Complete Bash Scripting Guide
3. Variables
- Assigning variables: name="John"
- Accessing variables: echo $name
- No spaces around '=' during assignment.
- Use curly braces for clarity: echo ${name}
Complete Bash Scripting Guide
4. Conditionals
if [ condition ]; then
commands
elif [ condition ]; then
commands
else
commands
fi
Example:
if [ $age -ge 18 ]; then
echo "Adult"
fi
Complete Bash Scripting Guide
5. Loops
- For loop:
for i in 1 2 3; do
echo $i
done
- While loop:
while [ condition ]; do
commands
done
- Until loop:
until [ condition ]; do
commands
done
Complete Bash Scripting Guide
6. Functions
function_name() {
commands
# or
function function_name {
commands
}
Complete Bash Scripting Guide
7. Arrays
array=("apple" "banana" "cherry")
echo ${array[1]} # banana
echo ${#array[@]} # number of elements
for i in "${!array[@]}"; do
echo "$i => ${array[$i]}"
done
Complete Bash Scripting Guide
8. String Manipulation
${#var} # Length of string
${var:pos:len} # Substring
${var/pattern/replace} # Replace pattern
Complete Bash Scripting Guide
9. File Test Operators
-e file : file exists
-f file : regular file
-d file : directory
-r file : readable
-w file : writable
-x file : executable
Complete Bash Scripting Guide
10. Useful Commands
- echo, read, printf
- date, whoami, uname
- grep, sed, awk
- cut, sort, uniq, wc
Complete Bash Scripting Guide
11. Script Arguments
$0 - script name
$1 to $9 - first 9 arguments
$# - number of arguments
$@ - all arguments
Complete Bash Scripting Guide
12. Exit Status and Traps
- $? holds exit status of last command
- exit N exits with status N
- trap 'commands' SIGNAL handles signals (e.g., INT, TERM)
Complete Bash Scripting Guide
13. Debugging and Best Practices
- Use set -x for debugging
- Validate inputs
- Use quotes to prevent word splitting
- Use functions for reusable code
- Always check exit statuses