Special Shell Parameters
In shell scripting, specific variables provide information about the execution environment. These can be referenced with or without braces (e.g., $var vs ${var}).
| Variable | Description |
|---|---|
$0 |
The name of the script itself. |
$1 - $9 |
The Nth argument passed to the script. |
$# |
Count of arguments passed (excluding $0). |
$@ |
List of all arguments as separate strings. |
$* |
All arguments combined into a single string, separated by the first cahracter of IFS. |
$$ |
Process ID (PID) of the current script. |
$! |
PID of the most recent background command. |
$? |
Exit status of the last executed command (0 indicates success). |
$- |
Current flags set in the shell. |
File Test Operaotrs
These operators are used within conditional statements (like if [ ... ]) to check file properties.
# Check existence
if [ -e "$config_file" ]; then
echo "File exists."
fi
# Check file type
[ -f "$target" ] # Regular file?
[ -d "$target" ] # Directory?
[ -L "$target" ] # Symbolic link?
[ -b "$target" ] # Block special file?
# Check attributes
[ -s "$target" ] # File exists and size > 0
[ -r "$target" ] # Readable?
[ -w "$target" ] # Writable?
[ -x "$target" ] # Executable?
[ -O "$target" ] # Owned by current user?
# Compare timestamps
if [ "/var/log/app.log" -nt "/var/log/app.log.bak" ]; then
echo "Current log is newer."
fi
if [ "/var/log/app.log" -ot "/var/log/app.log.bak" ]; then
echo "Current log is older."
fi
Arithmetic and Logical Operators
Operators used for integer comparisons and string logic.
# Integer Comparisons
[ $val1 -eq $val2 ] # Equal
[ $val1 -ne $val2 ] # Not equal
[ $val1 -lt $val2 ] # Less than
[ $val1 -gt $val2 ] # Greater than
[ $val1 -le $val2 ] # Less than or equal
[ $val1 -ge $val2 ] # Greater than or equal
# Logical Operators
[ -z "$string" ] # True if string is empty
[ $cond1 -a $cond2 ] # Logical AND (within single brackets)
[ $cond1 -o $cond2 ] # Logical OR (within single brackets)
# Control flow short-circuits
command1 && command2 # Run command2 only if command1 succeeds
command1 || command2 # Run command2 only if command1 fails
Process Control and Utilities
Managing script behavior and signals.
# Trap signals to handle interrupts (e.g., Ctrl+C)
# This script ignores SIGINT, SIGQUIT, and SIGTSTP
trap - INT QUIT TSTP
# Setting positional parameters manually
set alpha beta gamma
echo $1 # Output: alpha
echo $2 # Output: beta
echo $3 # Output: gamma