Wednesday, December 3, 2014

Fun with Bash Brace

Following results are tested on bash version 4.1.2.

1. Brace Expansion:

$ echo @{a,b,c,d}
@a @b @c @d

$ echo @{a,b,c,d}@
@a@ @b@ @c@ @d@

$ echo {5..12}
5 6 7 8 9 10 11 12

$echo {01..10}
01 02 03 04 05 06 07 08 09 10

$ echo 1.{0..9}
1.0 1.1 1.2 1.3 1.4 1.5 1.6 1.7 1.8 1.9

$ echo --{A..E}--
--A-- --B-- --C-- --D-- --E--

$ echo {A..C}{0..9}
A0 A1 A2 A3 A4 A5 A6 A7 A8 A9 B0 B1 B2 B3 B4 B5 B6 B7 B8 B9 C0 C1 C2 C3 C4 C5 C6 C7 C8 C9

$ echo {{A..F},{a..e}}
A B C D E F a b c d e

$ echo {1..10..2}
1 3 5 7 9
* 2 is increment value in above example

2. Parameter Substitution:

Length of variable ${#var}:

$ abc=bash
$ echo ${#abc}
4

Remove pattern (front) ${var#Pattern}:

$ f="/etc/resolv.conf"
$ echo ${f#/etc/}
resolv.conf

Remove pattern (back) ${var%pattern}:

$ FILE="xcache-1.3.0.tar.gz"
$ echo ${FILE%.tar.gz}
xcache-1.3.0

Find and Replace ${varName/Pattern/Replacement}:

$ x="Use unix or die"
$ echo "${x/unix/linux}"
Use linux or die

Following is a reference for bash parameter substitution operators:


No comments: