Wednesday, November 13, 2013

Linux - Back To Basic Part 2 - Shell Parameter Substitution $ and ${...}

Back to basic..

In my last post regarding Command Line Processing, it talks about how shell handle command line.

This post, it will talk more about Parameter Variable Substitution.

Parameter variable substitution happens at step 5 during command line processing. In general, it substitutes any expression that start with $ sign or ${...}

Let's assume that we had declare a variable ABC with

export ABC=foo

The most common form of parameter variable substitution is

echo $ABC

So, during command line processing, $ABC will be substitute with foo and the actual command is echo foo
As such, the result is

foo

What about ${...}? The shot answer is $PARAM = ${PARAM}

So, for our example, echo $ABC has the same result as ${ABC}. That is, it will echo foo

Actually, that all and as simple as this. The remaining part are common manipulating variable with ${...} syntax and the discussion are based on the scenario given above

1. ${PARAM}

As discussed, ${ABC} = $ABC and will return foo as result.

2. ${PARAM-DEFAULT} or ${PARAM:-DEFAULT}

This command provide a default value for your parameter. For example, if ABC is not set, echo ${ABC-'bar'} will echo bar as output. Please not that it will not set ABC to bar. If ABC is set to foo, it will echo foo as output

3. ${PARAM=DEFAULT} or ${PARAM:-DEFAULT}

This command will set parameter to default value if parameter is not set. For example, if ABC is not set, echo ${ABC=bar} will set ABC to bar and echo bar as output. If ABC is already set to foo, the command will modify ABC and echo foo as output

4. ${PARAM+ALT_VALUE} or ${PARAM:+ALT_VALUE}

This command will set parameter to an alternative value given if parameter is set. For example, if ABC is set to foo, echo ${ABC+bar} will echo bar as output. Please note that it will not set ABC to bar. If ABC is not set, echo ${ABC+bar} will echo null

The above are the common usage of ${...} and there are more to it. You can see the give reference for further details.

Reference http://tldp.org/LDP/abs/html/parameter-substitution.html

No comments:

Post a Comment

Oracle - Reclaim disk space

Oracle does not release disk space even if you had delete the data or tablespace. If you have enterprise manager, you should use it to  rec...