Pcornel
Linux · Shell & Bash

Functions

Cheat sheet · https://pcornel.dk/topic.php?topic=2690

Back to the Topic

Answer

A Bash function groups commands under a name: name() { …; }. It takes arguments as $1, $2, $@, returns an exit status with return, and runs in the current shell.

Remember

return only sets the exit status (0–255); output data with echo and capture it with $( ). Declare variables with local to avoid overwriting globals. Functions shadow commands of the same name.

First checks

  • bash -x script.sh — trace each expanded command
  • bash -n script.sh — syntax check only
  • shellcheck script.sh — common bugs and quoting problems
  • echo $? — exit code of the last command

Verify in this order

function defined → called with arguments → runs in the current shell → output written, status returned

Where it usually breaks

First mismatch in persistent intent → provider/parser/generator → kernel/userspace runtime → dependency/security context → logs/counters → consumer-visible read-back; preserve identity/native diagnostic/pre-state before mutation.

Read-only verification commands unless stated otherwise. Confirm syntax for your platform and release. Full reference: https://pcornel.dk/topic.php?topic=2690

Confirmation

Confirm action

Continue?