Skip to content

Instantly share code, notes, and snippets.

@AlexAtkinson
Created April 10, 2024 04:38
Show Gist options
  • Save AlexAtkinson/38b618f0aa42a1fd296af8e4902e368a to your computer and use it in GitHub Desktop.
Save AlexAtkinson/38b618f0aa42a1fd296af8e4902e368a to your computer and use it in GitHub Desktop.
BASH Cheatsheet

BASH

Brace Expansion

🗒️ +(...) is part of extended globs, you need to enable them explicitly with shopt -s extglob

🗒️ expansions support glob -NOT- regex

https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Shell-Expansions https://www.gnu.org/savannah-checkouts/gnu/bash/manual/bash.html#Pattern-Matching

${var}            Value of var, same as $var
${var,,}          lowercase
${var^^}          UPPERCASE
${#var}           Returns the length in characters
${var-DEFAULT}    If var not set, evaluate expression as $DEFAULT *
${var:-DEFAULT}   If var not set OR null, evaluate expression as $DEFAULT *
${var=DEFAULT}    If var not set, evaluate expression as $DEFAULT *
${var:=DEFAULT}   If var not set, evaluate expression as $DEFAULT *
${var+OTHER}      If var set, evaluate expression as $OTHER, otherwise as null string
${var:+OTHER}     If var set, evaluate expression as $OTHER, otherwise as null string
${var?ERR_MSG}    If var not set, print $ERR_MSG *
${var:?ERR_MSG}   If var not set OR null, print $ERR_MSG *
${!varprefix*}    Matches all previously declared variables beginning with varprefix (works with arrays)
${!varprefix@}    Matches all previously declared variables beginning with varprefix (works with arrays)
#                 shorted matching
##                longest matching
${var/foo/bar}    Replace FIRST MATCH
${var/foo}        DELETE first match
${var//foo}       DELETE all matches
${var/%foo/bar}   Replace SUFFIX
${var/%foo}       DELETE SUFFIX
${var%%foo/bar}   Replace LONG SUFFIX
${var/#foo/bar}   Replace PREFIX
${var/#foo}       DELETE PREFIX
${var##foo/bar}   Replace LONG PREFIX
${var//foo/bar}   Replace ALL instances of foo with bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment