Doing variable expansion in Bash, like a boss
I should have called this, how to kick sed off my living room couch, and
tell that lazy scumbag to go out and get a job and stop drinking all my
beer. But that was too long.
TL;DR
You can do just about anything inside two {}'s; the laws of nature no longer apply in there..
Substrings
$ export MYVAR=/usr/bin/eric.rocks
$ unset NULLVAR
$ echo ${MYVAR:1}
usr/bin/eric.rocks
$ echo ${MYVAR:9}
eric.rocks
$ echo ${MYVAR:9:4}
eric
# variable name wildcards
$ echo ${!MY*}
MYVAR
$ echo ${!DI*}
DIRSTACK DISPLAY
# '##' removes a prefix (accepts wildcards)
$ echo ${MYVAR##/usr}
/bin/eric.rocks
$ pwd
/usr/bin
$ echo ${MYVAR##$( pwd )}
/eric.rocks
# '%' remove the suffix (non-greedy)
$ echo ${MYVAR%.rocks}
/usr/bin/eric
# '%%' removes it greedily
$ echo ${MYVAR%r*}
/usr/bin/eric.
$ echo ${MYVAR%%r*}
/us
$ echo ${MYVAR%%ic}
/usr/bin/eric.rocks
$ echo ${MYVAR%%ic*}
/usr/bin/er
Substitution
${parameter/pattern/string}
# pattern accepts filename-type wildcards
$ echo ${MYVAR/e/f}
/usr/bin/fric.rocks
$ echo ${MYVAR/e*c/f}
/usr/bin/fks
# '#' means match from beginning
$ echo ${MYVAR/#\/*c/f}
fks
# '//' means replace all instances
$ $ echo ${MYVAR/S/e}
ACCEeS DENIED
$ echo ${MYVAR//S/e}
ACCEee DENIED
Transformations
# '^^' uppercases it
$ echo ${MYVAR^^}
/USR/BIN/ERIC.ROCKS
$ echo ${MYVAR^*}
/usr/bin/eric.rocks
$ echo ${TERM^*}
Screen
# ',' and ',,' lowercases it
$ export MYVAR="ACCESS DENIED"
$ echo ${MYVAR,}
aCCESS DENIED
$ echo ${MYVAR,,}
access denied
Returning Default Values
$ export MYVAR=/usr/bin/eric.rocks
$ unset NULLVAR
# return default "test" if unset
$ echo ${MYVAR:-test}
/usr/bin/eric.rocks
# return default value if unset
$ echo ${NULLVAR:-test}
test
# return, and assign, default value if unset
$ echo ${NULLVAR:=test}
test
$ set |grep NULLVAR
NULLVAR=test
$ unset NULLVAR
# return error message if unset
$ echo ${NULLVAR?aaaaaah}
-bash: NULLVAR: aaaaaah
# return value if set
$ echo ${MYVAR:+$TERM}
screen
# return nothing if unset
$ echo ${NULLVAR:+$TERM}
blog comments powered by Disqus