Did you know Bash is this powerful ?

A couple of interesting bash stuff I found on the www:
(It's Public Domain)

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
11. ${var:?”message”} -That prints message if varible does not exist,${var:-word},…

Most of them are from this blog:
http://bashcurescancer.com/
(not a big fan of the name though)

Comments