> ## Documentation Index
> Fetch the complete documentation index at: https://siriusbar.net/llms.txt
> Use this file to discover all available pages before exploring further.

# Functions and Debugging

> Bash functions, local variables, return statuses, and xtrace debugging.

## Functions

Functions in Bash are named blocks of shell commands. Bash executes the block in the current shell environment when we call the function. Two common ways to define them:

```bash theme={null}
# Method 1
function my_func {
  # ...
}

# Method 2
my_func() {
  # ...
}
```

Both work in Bash. The second form is also portable to POSIX-compatible shells, while the `function` keyword is Bash-specific. We call a function just by its name: `my_func`.

## Local Variables

Assignments inside a function affect global variables by default. If we want a variable local to the function call, we use the `local` keyword:

```bash theme={null}
var="I am global"

my_func() {
  local var="I am Local"
  echo "$var"
}

my_func    # prints "I am Local"
echo "$var"  # prints "I am global"
```

The local `var` temporarily hides the global `var`, so changing it does not change the global value. Bash uses dynamic scoping, which means functions called from `my_func` can also see this local variable while `my_func` is running.

## Passing Parameters

We pass parameters to functions the same way as script arguments — they are accessed with `$1`, `$2`, etc. inside the function:

```bash theme={null}
greet() {
  echo "Hello $1"
}

greet "world"   # Hello world
```

## Return Values

Bash functions return an exit status from `0` to `255`, not a general value like a C function. Some common statuses are:

| Code  | Meaning                                           |
| ----- | ------------------------------------------------- |
| `0`   | Success                                           |
| `1`   | General failure by convention                     |
| `2`   | Often used for incorrect command or builtin usage |
| `126` | Command found but not executable                  |
| `127` | Command not found                                 |

We set a function's status with `return N`. Without an explicit `return`, the function uses the status of its last command. We access the most recent exit status with `$?`.

## Debugging

```bash theme={null}
bash -x script.sh
```

This enables xtrace debugging. Can't really write the whole debug output here lmao :D. Basically, Bash prints commands after expanding variables and other substitutions, just before it executes them. Really useful when a script is silently failing and we have no idea where.

One warning: xtrace can expose passwords, tokens and other secrets contained in commands, so we should check the output before saving or sharing it.
