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.
Incorrect. Combining function and () is not the portable POSIX form.
cleanup() { rm -f -- "$tmp"; }Correct. cleanup() { ...; } is valid POSIX shell syntax.
Correct. cleanup() { ...; } is valid POSIX shell syntax.
cleanup = () { rm -f -- "$tmp"; }Incorrect. The assignment operator does not belong in a function definition.
Incorrect. The assignment operator does not belong in a function definition.
cleanup: { rm -f -- "$tmp"; }Incorrect. A colon does not define a shell function.
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
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.