Bash scripting tips

Bash is almost a complete programming language, I use every day (switching from the default tcsh in the servers, in Mac OS X is default) for automatic job launching.

Extracted from: http://hacktux.com/bash/script/efficient.

  1. Avoid full paths to bash built-ins. Except when you require specific commands, when I use systems with 32 or 64b binaries, I need to specify which one to use, or define an specific directory to use in the PATH or as a variable.
  2. Avoid external commands for integer math. Because bash has math evaluation.

  3. Avoid using cat. Commonly people use cat and send to other commands with a pipe, but many commands can read files in the parameters.

  4. Avoid piping grep to awk. Because awk can filter the inputs, use /pattern/

  5. Avoid piping sed to sed. Multiple filters can be applied to the input with the -e option ( sed -e "s/this/that/" -e "s/old/new/" filename ).

  6. Use double brackets for compound and RegEx tests. [[ ]] evaluate the operations between, ( if [[ expr1 && expr2 ]]; then something; fi )

  7. Use functions for repetitive tasks. Define some functions is simple ( function () { do_something; return $? } )

  8. Use Arrays Instead of multiple variables. Yes, bash has array support, declare as normal variables, and access with []. ARRAY = ("one", "two"); echo ${ARRAY[0]}

  9. Use /bin/mktemp to create temp files. This is new for me, good to know. tempfile = /bin/mktemp

  10. Use /bin/egrep or /bin/sed for RegEx pattern matching. Only for basic RegEx, for more complex patterns it's better to use Perl.


Comments

Popular posts from this blog

PS3 cluster

Ubuntu Cluster - Slave nodes