Parameter Substitution/Expansion

Please click the following link to get to the:  Bashscript Forum Board.  

1. Shell variables can be specified like $var or this ${var}.
$ var=’a.ads,fssd2342%asd234#@.,&%,sdfgsdfgas4352′
echo ${var}
a.ads,fssd2342%asd234#@.,&%,sdfgsdfgas4352

2. ${#var} is the length of the variable.
$ echo ${#var}
42

3. ${var:pos} substrings the variable starting at pos.
$ echo ${var:10}
2342%asd234#@.,&%,sdfgsdfgas4352

4. ${var:pos:len} substrings the variable starting at
pos with a max length of len.
$ echo ${var:10:5}
2342%

5. ${var#pattern} strips pattern from the front or left hand side
of the variable. This form is not greedy meaning it stops as
soon as the pattern is matched.
${var##pattern} is the greedy form.
$ echo ${var#*,}
fssd2342%asd234#@.,&%,sdfgsdfgas4352
$ echo ${var##*,}
sdfgsdfgas4352

6. ${var%pattern} strips pattern from the back or right hand side
of the variable. This form is not greedy meaning it stops as soon
as the pattern is matched.
${var%%pattern} is the greedy form.
$ echo ${var%,*}
a.ads,fssd2342%asd234#@.,&%
$ echo ${var%%,*}
a.ads

7. ${var/pattern/replacement} replaces pattern with replacement once.
$ echo ${var/a/A}
A.ads,fssd2342%asd234#@.,&%,sdfgsdfgas4352

8. ${var//pattern/replacement} replaces pattern with replacement globally.
$ echo ${var//a/A}
A.Ads,fssd2342%Asd234#@.,&%,sdfgsdfgAs4352

9. ${var/#pattern/replacement} if variable beginning matches the pattern
it is replaced with replacement.
$ echo ${var/#a./llll}
llllads,fssd2342%asd234#@.,&%,sdfgsdfgas4352

10. ${var/%pattern/replacement} if variable end matches the pattern
it is replaced with replacement.
$ echo ${var/%352/llll}
a.ads,fssd2342%asd234#@.,&%,sdfgsdfgas4llll

I’m not postive, but I think the above originally came from http://bashcurescancer.com/10-steps-to-beautiful-shell-scripts.html which seems to be defunct now… if this is your code and you would like it attributed to you or removed, please post in the forum or email me.

More useful links on this:

http://www.cyberciti.biz/tips/bash-shell-parameter-substitution.html

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