Bash shell nicest scripting features

  toucheatout  2007-08-15 16:02  Linux  

Linux's bash shell is certainly one of the most comfortable shells around. While reading its (4800+ lined) man page is certainly worth it, here are highlighted some features.

Pattern matching

This feature derives from the evaluation of a conditional expression, in the [[ expression ]] form. Pattern matching occurs with == and !=, though the most powerful operator is =~, as it allows backreferencing portions of the matched (extended) expression (similarly to what is commonly done with sed and perl), through the BASH_REMATCH array.

$ DATE=`date +%Y%m%d`
$ echo $DATE
20070815
$ [[ $DATE =~ '([0-9]{4})([0-9]{2})([0-9]{2})' ]] && echo We are day ${BASH_REMATCH[3]}, month ${BASH_REMATCH[2]} in year ${BASH_REMATCH[1]}
We are day 15, month 08 in year 2007

It may come handy on some data inputs or filenames (the result can also be attained with substrings, see below).

String manipulation

Substring are easily obtained using the ${VAR:offset[:length]} form. To surf on the last example,

$ DATE=`date +%Y%m%d`
$ echo $DATE
20070815
$ echo We are day ${DATE:6}, month ${DATE:4:2} in year ${DATE:0:4}
We are day 15, month 08 in year 2007

Length of a variable is also directly obtained - mnemonic : same character as number of arguments in a script

$ echo ${#DATE}
8

Arithmetic expressions

Simply obtained using $(( expression )). For instance the date in 3 days

$ echo $(($DATE + 3))
20070818

 
Informatics


yro.slashdot.org - Your Rights online


nytimes.com New York Times - International


Informatic headlines