Define a function and return a status
#Functions run in the current shell environment unless invoked in a subshell. return exits a function; exit ends the shell process.
Fragment
Reference
Read commands, quoting, streams, paths and scripts.
POSIX sh (2017 baseline), Bash additions and named Unix tools. Examples are independent fragments; file paths are illustrative. Bash-only syntax is labeled. macOS and Linux utility flags can differ.
POSIX sh docs getopts utility ↗
Functions run in the current shell environment unless invoked in a subshell. return exits a function; exit ends the shell process.
Fragment
sh file runs a script in a new shell. . file reads it in the current environment. A shebang selects an interpreter when a script is executed directly.
Fragment
Use #!/usr/bin/env bash for Bash scripts when Bash is resolved through PATH. Do not source an untrusted file.
& starts asynchronous work. $! is the most recent background process ID. wait returns its completion status.
Fragment
Track the process you started; a port number alone is not process ownership.
trap installs a shell action for a signal or shell exit. SIGTERM requests termination; a program may handle it. SIGKILL cannot be trapped.
Fragment
Cleanup should be safe to repeat; signals do not guarantee every descendant has stopped.
set -u reports many unset-parameter uses. set -e exits on some failures but has context-dependent exceptions, including condition tests and parts of command lists.
Fragment
Check important statuses explicitly; set -e does not make every failure fatal.
$0 names the script or shell invocation; $1 is the first argument and $# is the remaining count. Braces are required for ${10}. shift removes leading positional arguments.
Fragment
Check the count before reading a required parameter or shifting.
getopts parses declared short options; a colon after a letter requires its argument. A leading colon enables explicit missing/unknown-option handling. OPTIND is the next argument index.
Fragment
This parses short options, not GNU-style long options. Reusing getopts in one shell may require resetting OPTIND=1.
POSIX sh has no portable local declaration. Function assignments affect the current shell environment; use explicit names or a subshell when isolation is required.
Fragment
This function body uses a subshell, so assignments and directory changes do not escape.
ps can show a known process’s identity and parent. kill sends a signal; TERM requests termination and allows cleanup. Exit is not guaranteed until you observe completion.
Fragment
worker_pid must identify your own recorded child process for wait. PID reuse matters; inspect identity when operating later.