Shell Programming/Expansions


Expansions are required to deliver a value to script. We will discuss arithmetic expansion and parameter expansion here. Placing '$' prior to a variable expands its value.

Arithmetic expressions

edit

Arithmetic expansion is not part of portable shell syntax, but was added as a POSIX extension. Arithmetic expansion is achieved using a $((operation)) construct. Parameter expansion is achieved by using a ${parameter} construct.

Let's give an example of arithmetic expansion:

one=1
$(($one+1))

$(($one+1)) will have the value of 2.

String manipulation

edit

Let's try to do some examples for parameter expansion. Let's say we want to remove a string 'Hello' from 'HelloBob'. The following will do the trick:

string='HelloBob' 
${string%Bob}

${string%Bob} portion cuts out 'Bob' from end of variable string, so we are left with Hello as its output.

If variable string had value of 'HelloBobBob', ${string%%Bob*} would do the same trick. The '%%' portion is required because it signifies to remove the longest pattern matching 'Bob*'. So, we are also left with 'Hello'.

If '%' is replaced with '#' and '%%' replaced with '##', this signifies the same meaning but this time from beginning of parameter, not from end. For example, the following code would remove 'Hello' from 'HelloBobBob':

${string#Hello}

Conditional variable values

edit

Following subsections represent a syntax for handling of situations, where variable may be undefined.

${param-value}

Use 'value' if param's original value is null, otherwise value of param variable is taken.

${param?value}

Use param if defined, otherwise print value to output – it effectively aborts the command.

${param+value}

Use 'value' if param is defined (otherwise an empty string).

${param=value}

Use 'value' and set param to 'value' if param is undefined.

Besides the above-mentioned syntax, there is also a syntax with a colon preceding the -/?/+/=, eg.:

${param:?Parameter param must be set and non-empty}

Which for all four operators above causes that empty variables are handled in the same way as undefined ones in the above-mentioned definition.