I constantly fight with the decision of how to declare a variable or function in Bash.
Given the following assumptions:
- Bash is the only scripting language available.
- Naming conventions are irrelevant.
In the case of global variables should I use:
foo=bar– inside and outside of functions?declare -g foo=bar– inside and outside of functions?local -g foo=bar– inside of functions?
In the case of local variables should I use:
local foo=bardeclare foo=bar
In the case of read-only variables should I use:
declare -r foo=barlocal -r foo=barreadonly foo– following [1.] or [2.] without the-rflag on the next line.
In the case of functions should I use:
foo() { echo bar; }foo { echo bar; }function foo() { echo bar; }function foo { echo bar; }
In order to forget about it I define the following near the top of my
.bashrcas well as each of my Bash shell script files:The above definitions allow me to say for example:
def foo { echo bar; }.final foovar foo=barval foo=barAs indicated by the comments you can mix and match various variable flags such as
var -g foo=barfor a global (-g) variable (var) orval -Ai foobar=([foo]=0 [bar]=1)for a read-only (val), associative array (-A) consisting of integer (-i) values.Implicit variable scoping too comes with this approach. Also the newly introduced keywords
def,val,varandfinalshould be familiar to any software engineer who programs in languages such as JavaScript, Java, Scala and the like.