Skip to content

Instantly share code, notes, and snippets.

@albertywu
Last active March 9, 2021 20:05
Show Gist options
  • Select an option

  • Save albertywu/e213a02a853f2611775e9517b06ff745 to your computer and use it in GitHub Desktop.

Select an option

Save albertywu/e213a02a853f2611775e9517b06ff745 to your computer and use it in GitHub Desktop.
bash parameter substituation

cheat sheet for https://tldp.org/LDP/abs/html/parameter-substitution.html


Variable existence checking

${var:?}          # returns exit-code 1 if var not defined or null
${var:?err_msg}   # prints err_msg and returns exit-code 1 if var not defined or null

Variable defaulting

${var:-default}   # returns var if defined and non-null, else default

Variable length

${#var}           # prints length of var to stdout
${#var[@]}        # prints length of array var to stdout

Substring

${var:pos:len}    # get substring starting at pos (zero-indexed), with length len
${var:pos}        # get substring starting at pos (zero-indexed) until end of string

Removing prefixes & suffixes from a bash variable

${var#Pattern}    # remove shortest prefix that matches Pattern
${var##Pattern}   # remove longest prefix that matches Pattern
${var%Pattern}    # remove shortest suffix that matches Pattern
${var%%Pattern}   # remove longest suffix that matches Pattern

Replacing things in a bash variable

${var/Pattern/Replacement}  # replace first occurance of Pattern with Replacement
${var//Pattern/Replacement} # globally replace Pattern with Replacement
${var/#Pattern/Replacement} # replace prefix Pattern with Replacement
${var/%Pattern/Replacement} # replace suffix Pattern with Replacement
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment