Results for “Function scope & composition”
Small, practical examples. Search by task or narrow things down below.
Give a function its own positional parameters
Bash Scripts: A function receives its call arguments without replacing the caller’s positional parameters.
Bash Scripts✓ Tested
Keep a function variable local
Bash Scripts: Local prevents an ordinary function assignment from replacing a caller variable.
Bash Scripts✓ Tested
Load functions from a trusted local script
Bash Scripts: Source executes a file in the current shell so its function definitions remain available.
Bash Scripts✓ Tested
Use a function’s exit status as a boolean result
Bash Scripts: Return zero for success and test the function directly in a conditional.
Bash Scripts✓ Tested
Use a recursive function for a bounded calculation
Bash Scripts: A recursive factorial demonstrates local variables and a clear base case.
Bash Scripts✓ Tested
Capture output while handling a failed command
Bash Scripts: An assignment inherits the status of its command substitution, allowing both output and status to be handled.
Bash Scripts✓ Tested
Isolate variable changes in a subshell
Bash Scripts: Parentheses create a subshell whose variable assignments do not change the parent.
Bash Scripts✓ Tested
Observe command substitution’s trailing-newline removal
Bash Scripts: Command substitution removes trailing newlines while preserving embedded ones.
Bash Scripts✓ Tested
Return a value through a named output variable
Bash Scripts: A Bash nameref can update a caller-supplied variable without command substitution.
Bash Scripts✓ Tested
Return an array through a nameref
Bash Scripts: Assign through a nameref to preserve array element boundaries.
Bash Scripts✓ Tested
Limit a beginner function variable to local scope
Bash Scripts: Limit a beginner function variable to local scope with a small standalone Bash program.
Bash Scripts✓ Tested
Keep function-local assignments separate from caller state
PowerShell: Ordinary function assignments create local variables rather than replacing the caller’s variable.
PowerShell✓ Tested