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 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)) will have the value of 2.

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%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 'Bob' from end of variable string and do so further away from it. 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':


{param-value} replaces param's value with 'value' fi param's original value is null.

{param-?value} prints param: value if param doesn't exist or null. It effectively aborts the command. {param+value} sets param to value if not null.

Last modified on 4 July 2011, at 19:37