{"id":11620,"date":"2019-03-15T01:45:41","date_gmt":"2019-03-15T01:45:41","guid":{"rendered":"http:\/\/www.appservgrid.com\/paw92\/?p=11620"},"modified":"2019-03-15T01:45:41","modified_gmt":"2019-03-15T01:45:41","slug":"10-useful-tips-for-writing-effective-bash-scripts-in-linux","status":"publish","type":"post","link":"https:\/\/www.appservgrid.com\/paw92\/index.php\/2019\/03\/15\/10-useful-tips-for-writing-effective-bash-scripts-in-linux\/","title":{"rendered":"10 Useful Tips for Writing Effective Bash Scripts in Linux"},"content":{"rendered":"<p><a href=\"https:\/\/www.tecmint.com\/category\/bash-shell\/\" target=\"_blank\" rel=\"noopener noreferrer\">Shell scripting<\/a>\u00a0is the easiest form of programming you can learn\/do in Linux. More so, it is a required skill for\u00a0<a href=\"https:\/\/www.tecmint.com\/using-shell-script-to-automate-linux-system-maintenance-tasks\/\" target=\"_blank\" rel=\"noopener noreferrer\">system administration for automating tasks<\/a>, developing new simple utilities\/tools just to mention but a few.<\/p>\n<p>In this article, we will share 10 useful and practical tips for writing effective and reliable bash scripts and they include:<\/p>\n<h3>1. Always Use Comments in Scripts<\/h3>\n<p>This is a recommended practice which is not only applied to shell scripting but all other kinds of programming. Writing comments in a script helps you or some else going through your script understand what the different parts of the script do.<\/p>\n<p>For starters, comments are defined using the\u00a0<code>#<\/code>\u00a0sign.<\/p>\n<pre>#TecMint is the best site for all kind of Linux articles<\/pre>\n<p>Sometimes bash may continue to execute a script even when a certain command fails, thus affecting the rest of the script (may eventually result in logical errors). Use the line below to exit a script when a command fails:<\/p>\n<pre>#let script exit if a command fails\r\nset -o errexit \r\nOR\r\nset -e\r\n<\/pre>\n<h3>3. Make a Script exit When Bash Uses Undeclared Variable<\/h3>\n<p>Bash may also try to use an undeclared script which could cause a logical error. Therefore use the following line to instruct bash to exit a script when it attempts to use an undeclared variable:<\/p>\n<pre>#let script exit if an unsed variable is used\r\nset -o nounset\r\nOR\r\nset -u\r\n<\/pre>\n<h3>4. Use Double Quotes to Reference Variables<\/h3>\n<p>Using double quotes while referencing (using a value of a variable) helps to prevent word splitting (regarding whitespace) and unnecessary globbing (recognizing and expanding wildcards).<\/p>\n<p>Check out the example below:<\/p>\n<pre>#!\/bin\/bash\r\n#let script exit if a command fails\r\nset -o errexit \r\n\r\n#let script exit if an unsed variable is used\r\nset -o nounset\r\n\r\necho \"Names without double quotes\" \r\necho\r\nnames=\"Tecmint FOSSMint Linusay\"\r\nfor name in $names; do\r\n        echo \"$name\"\r\ndone\r\necho\r\n\r\necho \"Names with double quotes\" \r\necho\r\nfor name in \"$names\"; do\r\n        echo \"$name\"\r\ndone\r\n\r\nexit 0\r\n<\/pre>\n<p>Save the file and exit, then run it as follows:<\/p>\n<pre>$ .\/names.sh\r\n<\/pre>\n<div id=\"attachment_25667\" class=\"wp-caption aligncenter\">\n<p><a href=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2017\/05\/Use-Double-Quotes-in-Scripts.png\"><img loading=\"lazy\" decoding=\"async\" class=\"size-full wp-image-25667\" src=\"https:\/\/www.tecmint.com\/wp-content\/uploads\/2017\/05\/Use-Double-Quotes-in-Scripts.png\" alt=\"Use Double Quotes in Scripts\" width=\"588\" height=\"211\" data-lazy-loaded=\"true\" \/><\/a><\/p>\n<p class=\"wp-caption-text\">Use Double Quotes in Scripts<\/p>\n<\/div>\n<h3>5. Use functions in Scripts<\/h3>\n<p>Except for very small scripts (with a few lines of code), always remember to use functions to modularize your code and make scripts more readable and reusable.<\/p>\n<p>The syntax for writing functions is as follows:<\/p>\n<pre>function check_root(){\r\n\tcommand1; \r\n\tcommand2;\r\n}\r\n\r\nOR\r\ncheck_root(){\r\n\tcommand1; \r\n\tcommand2;\r\n}\r\n<\/pre>\n<p>For single line code, use termination characters after each command like this:<\/p>\n<pre>check_root(){ command1; command2; }\r\n<\/pre>\n<h3>6. Use = instead of == for String Comparisons<\/h3>\n<p>Note that\u00a0<code>==<\/code>\u00a0is a synonym for\u00a0<code>=<\/code>, therefore only use a single\u00a0<code>=<\/code>\u00a0for string comparisons, for instance:<\/p>\n<pre>value1=\u201dtecmint.com\u201d\r\nvalue2=\u201dfossmint.com\u201d\r\nif [ \"$value1\" = \"$value2\" ]\r\n<\/pre>\n<h3>7. Use $(command) instead of legacy \u2018command\u2019 for Substitution<\/h3>\n<p><a href=\"https:\/\/www.tecmint.com\/assign-linux-command-output-to-variable\/\" target=\"_blank\" rel=\"noopener noreferrer\">Command substitution<\/a>\u00a0replaces a command with its output. Use\u00a0<code>$(command)<\/code>\u00a0instead of backquotes\u00a0<code>`command`<\/code>\u00a0for command substitution.<\/p>\n<p>This is recommended even by\u00a0<a href=\"https:\/\/www.tecmint.com\/shellcheck-shell-script-code-analyzer-for-linux\/\" target=\"_blank\" rel=\"noopener noreferrer\">shellcheck tool<\/a>\u00a0(shows warnings and suggestions for shell scripts). For example:<\/p>\n<pre>user=`echo \u201c$UID\u201d`\r\nuser=$(echo \u201c$UID\u201d)\r\n<\/pre>\n<h3>8. Use Read-only to Declare Static Variables<\/h3>\n<p>A static variable doesn\u2019t change; its value can not be altered once it\u2019s defined in a script:<\/p>\n<pre>readonly passwd_file=\u201d\/etc\/passwd\u201d\r\nreadonly group_file=\u201d\/etc\/group\u201d\r\n<\/pre>\n<h3>9. Use Uppercase Names for ENVIRONMENT Variables and Lowercase for Custom Variables<\/h3>\n<p>All bash environment variables are named with uppercase letters, therefore use lowercase letters to name your custom variables to avoid variable name conflicts:<\/p>\n<pre>#define custom variables using lowercase and use uppercase for env variables\r\nnikto_file=\u201d$HOME\/Downloads\/nikto-master\/program\/nikto.pl\u201d\r\nperl \u201c$nikto_file\u201d -h  \u201c$1\u201d\r\n<\/pre>\n<h3>10. Always Perform Debugging for Long Scripts<\/h3>\n<p>If you are writing bash scripts with thousands of lines of code, finding errors may become a nightmare. To easily fix things before executing a script, perform some debugging. Master this tip by reading through the guides provided below:<\/p>\n<ol>\n<li><a href=\"https:\/\/www.tecmint.com\/enable-shell-debug-mode-linux\/\" target=\"_blank\" rel=\"noopener noreferrer\">How To Enable Shell Script Debugging Mode in Linux<\/a><\/li>\n<li><a href=\"https:\/\/www.tecmint.com\/check-syntax-in-shell-script\/\" target=\"_blank\" rel=\"noopener noreferrer\">How to Perform Syntax Checking Debugging Mode in Shell Scripts<\/a><\/li>\n<li><a href=\"https:\/\/www.tecmint.com\/trace-shell-script-execution-in-linux\/\" target=\"_blank\" rel=\"noopener noreferrer\">How to Trace Execution of Commands in Shell Script with Shell Tracing<\/a><\/li>\n<\/ol>\n<p>That\u2019s all! Do you have any other best bash scripting practices to share? If yes, then use the comment form below to do that.<\/p>\n<p><a href=\"https:\/\/www.tecmint.com\/useful-tips-for-writing-bash-scripts-in-linux\/\" target=\"_blank\" rel=\"noopener\">Source<\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Shell scripting\u00a0is the easiest form of programming you can learn\/do in Linux. More so, it is a required skill for\u00a0system administration for automating tasks, developing new simple utilities\/tools just to mention but a few. In this article, we will share 10 useful and practical tips for writing effective and reliable bash scripts and they include: &hellip; <\/p>\n<p class=\"link-more\"><a href=\"https:\/\/www.appservgrid.com\/paw92\/index.php\/2019\/03\/15\/10-useful-tips-for-writing-effective-bash-scripts-in-linux\/\" class=\"more-link\">Continue reading<span class=\"screen-reader-text\"> &#8220;10 Useful Tips for Writing Effective Bash Scripts in Linux&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-11620","post","type-post","status-publish","format-standard","hentry","category-linux"],"_links":{"self":[{"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/posts\/11620","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/comments?post=11620"}],"version-history":[{"count":1,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/posts\/11620\/revisions"}],"predecessor-version":[{"id":11621,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/posts\/11620\/revisions\/11621"}],"wp:attachment":[{"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/media?parent=11620"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/categories?post=11620"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appservgrid.com\/paw92\/index.php\/wp-json\/wp\/v2\/tags?post=11620"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}