# Bash Variable Tricks

bash's built-in parameter expansion handles path manipulation, string replacement, substrings, case conversion and defaults — no piping to `sed` or `awk` for basic string stuff. it's kinda ugly looking but incredibly useful once you get the pattern down.

## splitting paths with `${file##*/}` and `${file%.*}`

this is the one I reach for most. say you have:

```bash
file="/home/user/docs/report.tar.gz"
```

```bash
${file##*/}    # report.tar.gz   (just the filename)
${file%/*}     # /home/user/docs  (just the directory)
${file%.*}     # /home/user/docs/report.tar  (drop last extension)
${file%%.*}    # /home/user/docs/report      (drop ALL extensions)
${file##*.}    # gz  (just the extension)
```

the trick to remembering: `#` chops from the left, `%` chops from the right. double means greedy. I still have to think about it sometimes tbh.

## replacing, slicing and case-converting with ${str/a/b}

replace things:

```bash
msg="hello world"
${msg/world/bash}     # hello bash  (first match)
${msg//o/0}           # hell0 w0rld (all matches)
```

substring:

```bash
str="abcdefgh"
${str:2:4}   # cdef
${str:5}     # fgh
${#str}      # 8 (length)
```

case conversion (bash 4+):

```bash
name="hello"
${name^}     # Hello (first letter)
${name^^}    # HELLO (all)
```

## defaults and fallbacks with ${VAR:-x}

instead of writing `if [ -z "$PORT" ]` everywhere:

```bash
${PORT:-8080}              # use 8080 if PORT is empty/unset
${PORT:=8080}              # same but also SET it
${DB_HOST:?'not set!'}     # crash with error if missing
${DEBUG:+'--verbose'}      # use '--verbose' only if DEBUG IS set
```

the `:=` one is great for scripts with optional config. the `:?` one is great for scripts with required config. I use both all the time.

## arrays: ${arr[@]}, ${#arr[@]} and slices

```bash
fruits=(apple banana cherry)
${fruits[0]}       # apple
${fruits[@]}       # all of them
${#fruits[@]}      # 3
${fruits[@]:1:2}   # banana cherry (slice)
```

remember if you're on zsh interactively, arrays start at 1 there. but `#!/bin/bash` scripts are always 0-indexed. don't let that bite you.

---

see also: [Bash Brace Expansion](/articles/bash-brace-expansion), [Bash Quick Loops](/articles/bash-quick-loops), [Bash History Expansion](/articles/bash-history-expansion)

[the bash man page on parameter expansion](https://man7.org/linux/man-pages/man1/bash.1.html#EXPANSION) — bookmark this one, it's dense but complete

the [bash hackers wiki](https://web.archive.org/web/20230406205817/https://wiki.bash-hackers.org/syntax/pe) had a great page on this too (archived now sadly)
