What is a Function in Shell Scripting?
A function in shell scripting is a named block of reusable code that performs a specific task. Instead of repeating the same commands multiple times, you can write them once in a function and call the function whenever needed.
________________________________________
✅ Key Features of Functions:
• Reusable: Write once, use multiple times.
• Organized: Breaks your script into logical blocks.
• Maintainable: Easier to update and debug.
• Flexible: Can accept input arguments (like $1, $2) and return output using echo.
________________________________________
📌 Function Syntax
function_name() {
commands
}
OR
function function_name {
commands
}
Calling the function
function_name
EX1: Taking backup
#!/bin/bash
Function to perform backup
backup_directory() {
src_dir="$1"
backup_base="$2"
timestamp=$(date +%F_%T)
backup_dir="${backup_base}/backup_${timestamp}"
Create backup directory
mkdir -p "$backup_dir"
Copy source to backup
cp -r "$src_dir" "$backup_dir"
echo "Backup of '$src_dir' completed at '$backup_dir'"
}
Call the function with source and destination
backup_directory /etc /tmp
Line-by-Line Explanation
1. #!/bin/bash – Shebang to use Bash shell.
2. backup_directory() – Declares a function named backup_directory.
3. src_dir="$1" – First argument: source directory (e.g., /etc).
4. backup_base="$2" – Second argument: base destination path (e.g., /tmp).
5. timestamp=$(date +%F_%T) – Gets current date and time (e.g., 2025-05-07_15:22:30).
6. backup_dir="${backup_base}/backup_${timestamp}" – Constructs full backup path.
7. mkdir -p "$backup_dir" – Creates the backup directory.
8. cp -r "$src_dir" "$backup_dir" – Recursively copies source to backup.
9. echo ... – Prints a confirmation message.
10. backup_directory /etc /tmp – Calls the function with source /etc and destination /tmp
コメント