Define cleanup in a script run by /bin/sh.
Do not depend on Bash's function keyword.
Which definition is appropriate?
name() { commands; } is the POSIX function form. The function keyword is a Bash extension.
Detailed explanation
function cleanup() { rm -f -- "$tmp"; }Incorrect. Combining function and () is not the portable POSIX form.
cleanup() { rm -f -- "$tmp"; }Correct. cleanup() { ...; } is valid POSIX shell syntax.
cleanup = () { rm -f -- "$tmp"; }Incorrect. The assignment operator does not belong in a function definition.
cleanup: { rm -f -- "$tmp"; }Incorrect. A colon does not define a shell function.
Try it yourself
An example you can run in a temporary verification environment.
sh -c 'cleanup() { printf "cleaned\n"; }; cleanup'Expected result
cleanedKey points
- name() is POSIX syntax
- function is a Bash extension
- The body runs in the current shell
Notes
- Environment: POSIX sh / 状態変更なし
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Shell function
A reusable group of commands that runs in the caller's shell context.
Positional parameter
A numbered argument or special value supplied to a script or function.
Control flow
Conditions, loops, and exit statuses determine which shell commands run.