Skip to content

Instantly share code, notes, and snippets.

@shaunlebron
Last active August 25, 2025 02:01
Show Gist options
  • Save shaunlebron/2d47d53981eb620c5c3bb1cc5955bd53 to your computer and use it in GitHub Desktop.
Save shaunlebron/2d47d53981eb620c5c3bb1cc5955bd53 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Cheatsheet for remembering Bash rules for Parameter Substitution:
# https://tldp.org/LDP/abs/html/parameter-substitution.html#PSUB2
# Fallback for unset vars
# Bash #——> like JavaScript
${a+b} #——> a && b
${a-b} #——> a || b
${a?b} #——> a || (print(b), exit(1))
${a=b} #——> a ||= b
# ^—————————> use colon prefix (i.e. :- := :+ :?) for null instead of unset
# String replacing
${a/b/c} #——> replace one
${a//b/c} #——> replace all
${a/#b/c} #——> replace at beginning
${a/%b/c} #——> replace at end
${a#b} #——> remove match from beginning (## for greedy)
${a%b} #——> remove match from end (%% for greedy)
# String length and substring
${#a} #——> string length
${a:b} #——> substring start
${a:b:c} #——> substring start and len
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment