← xoc3.io

2021-09-04 - all about bash vars

bash has a few ways to set vars and a few different var scopes. i'll go over a few concepts and provide examples for each one in this post.

start with the basics

there are 3 var scopes in bash. local, global, and exported. use the 'local' keyword to create local vars. local vars are only available in the same scope they're declared in. here is an example:

bash vars are global by default, so here is another example without the local keyword.

the difference between global and exported variables is that exported variables are also available in subshells. use the 'export' keyword to declare an exported variable:

careful with quoting

global variables are generally only available in the current shell, but declaring a global variable right before a command acts as exporting the variable just for the specific command.

single vs double quotes are important when using this syntax. here is a tricky example:

numeric vars

vars in bash are all strings, but you can do some arithmetic:

bash doesn't support decimals with the numeric syntax, but zsh does. bash also allows you to switch a numeric variable to a string, but zsh doesn't:

that's it for now. have fun shell scripting.