|
|
| |
|
Here we have some suggestions for you which may help you in keeping your Bash scripts neat and clean.
|
|
|
|
|
|
Monday, September 29, 2014:
Linux distributions' default command line interface, Bash, is a powerful
scripting language too. Writing bash scripts is not easy and and
writing efficient and clean ones is tougher. But if you are handful of
some helpful tips then no task seems to be a headache. So here we have
some suggestions for you which may help you in keeping your Bash scripts
neat and clean:
|
|
1. Avoid Full Paths to Bash Builtins:
There are many
builtins in Bash which can be utilised in place of calling external
commands. The commands can be leveraged whenever you find it suitable as
it doesn't call any subcommand from the system. Avoid using the full
path for these commands and use builtins. Refer to the Bash man page for a list of builtins.
2. Use Long Options:
Abbreviations
are not meant for efficiency in case of reusable scripts as these
scripts need some better and extra keystrokes and you should avoid
ventures into man pages regularly. Also make sure your collaborator in
the scripting project too follows the same rule.
3. Avoid External Commands for Integer Math:
There are builtins which can be used in integer arithmetic and integer calculations can also be performed with Bash builtins.
4. Exit Script When Command Fails:
You should make your script exit when a command fails and run commands to exit if your script tries to use undeclared variables.
5. Avoid using Cat:
There
are some tools which takes files as arguments like Grep, Awk and Sed.
Don't use bin/cat and instead you can use Grep's native ability to read
files.
6. Catch The Failures In Your Scripts:
You need to catch the fails in your scripts and make sure that the exit status of the last command is returned.
7. Use Double Brackets for Compound and Regex Tests:
Use
[ or test builtins to test expressions but keep in mind that [[
builtins provide compound commands and regular expression matching.
8. Use Functions for Repetitive Tasks:
You
need to break your script into pieces and conduct repetitive tasks
through certain functions. Your functions should be usable by more than
one shell script as you can source a function file from the various
scripts and the next file in Bash can be sourced using the . builtin.
9. Surround your variables with{}:
If
you don't follow this rule, remember the bash may try to access the
variable in the environment. Don't use two equal signs if you are
checking the script.
10. Use Arrays Instead of Multiple Variables:
Don't use unnecessary variables in Bash scripting as Bash arrays are quite powerful. Check out this article on Bash arrays for further reference.
Source: HACKTUX notes and kvz.io blog
|
|
0 comments:
Post a Comment