•Arnošt Havelka
Premium: Bash Script Functions
Write reusable functions to eliminate code duplication and build maintainable automation scripts.
Start Interactive LessonFunctions let you write a command once and call it many times. Master this pattern and your scripts become truly powerful.
Step 1: Define a Simple Function
Terminal
~$function check_status { echo 'Status OK'; }
check_status
A function is just a named block. Call it anytime without rewriting the code.
Step 2: Write Multi-Line Functions
Terminal
~$function backup_files {
mkdir -p backups
cp *.log backups/ 2>/dev/null
echo 'Files backed up'
}
backup_files
Each line in a function runs in sequence. Organize complex tasks into one reusable block.
Step 3: Use Functions with Variables
Terminal
~$function check_server {
echo "Checking server: $1"
}
check_server prod
The $1, $2, etc. are function arguments. Your function is now truly reusable with different inputs.
Checklist You Can Reuse
- Define with
function name { commands; }. - Call with
name arg1 arg2. - Reference arguments as
$1,$2,$@(all args). - Return exit codes with
return 0orreturn 1.
Knowledge Check
1 / 2How do you pass arguments to a bash function?
References
These documentation links provide authoritative details for the commands used in this article.
Up Next
Premium: Bash Script Automation
Combine loops and conditionals to build scripts that run tasks automatically and respond to system state.