bash variables

From Glee
Jump to: navigation, search

Overview

Simple changes to variables are often needed in shell scripts. It's common to see awk, perl or sed forked from the shell just to perform simple transformations, when bash could perfectly do them. It obviously doesn't matter to get the job done, but it's always best to optimize code, even when dealing with simple shell scripts.

man bash and check the "Parameter Expansion" section

String Modification

Pattern Substitution

${parameter/pattern/string} (first occurrence only) ${parameter//pattern/string} (all occurrences)

Example :

HOST=${HOSTNAME/.*/}
DIRS=${MYNAME//-/\/}

Pattern Prefix Removing

${parameter#word} (shortest matching) ${parameter##word} (longest matching)

Example :

RELATIVE_NAME=${FILE#/}

Pattern Suffix Removing

${parameter%word} (shortest matching) ${parameter%%word} (longest matching)

Example :

NOTLD=${HOSTNAME%.net}

Pattern Uppercasing

Note : This only works starting with bash 4.

${parameter^pattern} (shortest matching) ${parameter^^pattern} (longest matching)

Example :

FIRSTUPPER=${HOSTNAME^*}
ALLUPPER=${HOSTNAME^^*}

Pattern Lowercasing

Note : This only works starting with bash 4.

${parameter,pattern} (shortest matching) ${parameter,,pattern} (longest matching)

Example :

FIRSTLOWER=${HOSTNAME,*}
ALLLOWER=${HOSTNAME,,*}

Parameter Expansion

Use Default Values

${parameter:-word}

Example :

HOMEDIR=${HOME:-/home/`id -un`}

Assign Default Values

${parameter:=varname}

Example (which doesn't seem to work) :

HOMEDIR=${CUSTOM_HOME:=HOME}

Display Error if Null or Unset

${parameter:?word}

Example :

HOMEDIR=${HOME:?Variable not set}

Use Alternate Value

${parameter:+word}

Example :

MESSAGE=${DEBUG:+Debug is active}

Substring Expansion

${parameter:offset} and ${parameter:offset:length}

Example :

$ echo $HOME
/home/dude
$ echo ${HOME:6}
dude
$ echo ${HOME:1:4}
home