title: Zsh Variable Substitution tags: linux macos zsh variables ## Substrings Zsh uses the `$var[a,b]` syntax where it extracts the substring from `a` to `b` inclusive (`b` is position, not length like with `substr()`). Use `-1` for the end of the string. Indexing is 1-based, so `$var[1]` is the first character of `$var` if `$var` is not an array, else it is the first element of the array. ```bash % name="John" % echo $name[1,2] ``` ## Changing case to upper or lower Sources: [official docs](https://zsh.sourceforge.io/Intro/intro_12.html) and [scriptingosx.com](https://scriptingosx.com/2019/12/upper-or-lower-casing-strings-in-bash-and-zsh/) For zsh ```bash % name="John Doe" % echo ${name:l} john doe % echo ${name:u} JOHN DOE # Capitalise first letter, rest lowercase % name="jOHN" % echo "${name[0,1]:u}${name[2,-1]:l}" John ``` ## Arrays ```bash % a=(hello world mr flibble) % echo $a[1] hello % echo $a[3] mr % echo $a[3,4] mr flibble % echo $a[-1,-1] flibble % echo $a[-2,-1] mr flibble % echo $a[-1,-2] # blank ```