Handling Arrays and File Input
Reading external data into an array is a fundamental task in shell scripting. This allows for batch processing of file paths or configuration entries.
Reading File Lines into an Array
The following example demonstrates how to read a file line by line and store the contents into a Bash array for subsequent iteration.
#!/bin/bash
# Define the input file
input_list="manifest.txt"
# Initialize an empty array
buffer=()
# Populate the array line by line
while IFS= read -r entry; do
buffer+=("$entry")
done < "$input_list"
# Iterate through the array with a counter
idx=0
for item in "${buffer[@]}"; do
echo "Entry [$idx]: $item"
((idx++))
done
Conditional Logic and File System Checks
Shell scripts often need to verify the state of the environment before proceeding with operations like file writing or directory navigation.
Verifying Files and Directories
Using the [[ ... ]] construct provides a robust way to check for the existence of filesystem objects.
#!/bin/bash
target_path=$1
target_dir=$2
# Check if a file or directory exists
if [[ -e "$target_path" ]]; then
echo "Path '$target_path' was found."
else
echo "Path '$target_path' is missing."
fi
# Specifically check for a directory
if [[ ! -d "$target_dir" ]]; then
echo "Error: Directory '$target_dir' does not exist."
else
echo "Success: '$target_dir' is a valid directory."
fi
String and Numeric Comparisons
Bash supports both string-based and arithmetic comparisons within conditional blocks.
#!/bin/bash
status="active"
threshold=100
# String comparison
if [[ "$status" == "active" ]]; then
echo "System is online."
else
echo "System is offline."
fi
# Integer comparison
if [[ $threshold -ne 100 ]]; then
echo "Threshold mismatch."
else
echo "Threshold verified."
fi
Processing Command-Line Arguments
Effective scripts handle user input either through fixed positional parameters or flexible named options.
Positional Paramter Validation
This method relies on the specific order of arguments passed to the script.
#!/bin/bash
show_help() {
echo "Usage: $0 <username> <id> <role>"
}
# Ensure exactly three arguments are provided
if [[ $# -ne 3 ]]; then
show_help
exit 1
fi
echo "Processing User Data:"
echo "Name: $1"
echo "ID: $2"
echo "Role: $3"
Advanced Argument Parsing with getopt
For complex scripts, using getopt allows for standardized short (-h) and long (--help) options.
#!/bin/bash
usage_info() {
echo "Usage options:"
echo " -h, --help Display help"
echo " -p, --path Set file path"
echo " -v, --verbose Enable verbose mode"
}
# Define allowed options
VALID_OPTS="h,p:,v"
LONG_OPTS="help,path:,verbose"
PARSED_ARGS=$(getopt --options $VALID_OPTS --longoptions $LONG_OPTS --name "$0" -- "$@")
eval set -- "$PARSED_ARGS"
while true; do
case "$1" in
-h|--help)
usage_info
shift; exit 0
;;
-p|--path)
echo "Target Path: $2"
shift 2
;;
-v|--verbose)
echo "Verbose mode enabled"
shift
;;
--)
shift
break
;;
*)
echo "Internal error!"
exit 1
;;
esac
done
Defining and Invoking Functions
Functions help modularize code and improve readability. In Bash, functions can accept parameters and call other functions within the same script scope.
#!/bin/bash
# Function with local parameter handling
log_message() {
local timestamp=$(date +"%T")
echo "[$timestamp] Script: $0"
echo "Parameter 1: $1"
echo "Parameter 2: $2"
}
# Wrapper function
execute_task() {
echo "Starting task sequence..."
log_message "Job_Alpha" "Success"
}
# Execute the wrapper
execute_task