Script Arguments
Hard-coded scripts are limited. Arguments make them flexible and reusable.
Basic Arguments
Inside the script:
#!/bin/bash
echo "First argument: $1"
echo "Second argument: $2"
echo "Third argument: $3"
Special Variables
| Variable | Contains |
|---|---|
$0 | Script name |
$1 - $9 | Arguments 1-9 |
${10} | Argument 10+ (need braces) |
$# | Number of arguments |
$@ | All arguments (as separate words) |
$* | All arguments (as single string) |
#!/bin/bash
echo "Script name: $0"
echo "Argument count: $#"
echo "All arguments: $@"
Check Argument Count
#!/bin/bash
if [[ $# -lt 2 ]]; then
echo "Usage: $0 <source> <destination>"
exit 1
fi
source="$1"
dest="$2"
echo "Copying $source to $dest"
$@ vs $*
"$@" preserves argument boundaries. Use this one.
Loop Through Arguments
#!/bin/bash
# Process all files passed as arguments
for file in "$@"; do
echo "Processing: $file"
wc -l "$file"
done
Shift Arguments
shift removes the first argument, shifting others down:
#!/bin/bash
echo "Before shift: $1 $2 $3"
shift
echo "After shift: $1 $2 $3"
Useful for processing flags:
#!/bin/bash
while [[ $# -gt 0 ]]; do
case "$1" in
-v|--verbose)
VERBOSE=true
shift
;;
-o|--output)
OUTPUT="$2"
shift 2
;;
*)
FILES+=("$1")
shift
;;
esac
done
echo "Verbose: $VERBOSE"
echo "Output: $OUTPUT"
echo "Files: ${FILES[@]}"
Default Values
#!/bin/bash
# Use default if not provided
name="${1:-World}"
echo "Hello, $name!"
Practical Script Example
#!/bin/bash
# backup.sh - Flexible backup script
usage() {
echo "Usage: $0 [-c] [-o output_dir] source_dir"
echo " -c Compress backup"
echo " -o output_dir Destination (default: /backup)"
exit 1
}
# Defaults
COMPRESS=false
OUTPUT="/backup"
# Parse arguments
while [[ $# -gt 0 ]]; do
case "$1" in
-c)
COMPRESS=true
shift
;;
-o)
OUTPUT="$2"
shift 2
;;
-h|--help)
usage
;;
*)
SOURCE="$1"
shift
;;
esac
done
# Validate
if [[ -z "$SOURCE" ]]; then
echo "Error: Source directory required"
usage
fi
# Run backup
echo "Backing up $SOURCE to $OUTPUT"
if $COMPRESS; then
tar -czf "$OUTPUT/backup.tar.gz" "$SOURCE"
else
cp -r "$SOURCE" "$OUTPUT"
fi
echo "Done!"
What does $# contain?
Quick Reference
| Variable | Meaning |
|---|---|
$0 | Script name |
$1-$9 | Positional arguments |
$# | Argument count |
$@ | All args (preserved) |
$* | All args (single string) |
${var:-default} | Default value |
shift | Remove first argument |
Key Takeaways
$1,$2, etc. access positional arguments$#gives argument count - use for validation"$@"to loop through all arguments (preserves spacing)shiftmoves arguments down (for parsing flags)${1:-default}provides default values- Always validate arguments before using them
Congratulations! You've completed Chapter 12: Shell Scripting Basics.
Next chapter: Advanced Scripting - functions, error handling, and more.