•Arnošt Havelka
Premium: Bash Script Functions
Write reusable functions to eliminate code duplication and build maintainable automation scripts.
Start Interactive LessonPremium: Bash Script Functions
Functions 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
Command Prompt
Status OK
C:\Users\User>echo 'Status OK'
A function is just a named block. Call it anytime without rewriting the code.
Step 2: Write Multi-Line Functions
Command Prompt
Files backed up
C:\Users\User>echo 'Files backed up'
Each line in a function runs in sequence. Organize complex tasks into one reusable block.
Step 3: Use Functions with Variables
Command Prompt
Checking server: prod
C:\Users\User>echo 'Checking 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 Microsoft Learn and Windows documentation links provide authoritative details for the commands used in this article.