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.
Extracted from: http://hacktux.com/bash/script/efficient.
- 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.
- Avoid external commands for integer math. Because bash has math evaluation.
- Avoid using cat. Commonly people use cat and send to other commands with a pipe, but many commands can read files in the parameters.
- Avoid piping grep to awk. Because awk can filter the inputs, use /pattern/
- 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 ).
- Use double brackets for compound and RegEx tests. [[ ]] evaluate the operations between, ( if [[ expr1 && expr2 ]]; then something; fi )
- Use functions for repetitive tasks. Define some functions is simple ( function () { do_something; return $? } )
- Use Arrays Instead of multiple variables. Yes, bash has array support, declare as normal variables, and access with []. ARRAY = ("one", "two"); echo ${ARRAY[0]}
- Use /bin/mktemp to create temp files. This is new for me, good to know. tempfile = /bin/mktemp
- 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
Post a Comment