Declare Your Bash Variables

Everyone knows that “regular” Bash variables are just strings. Bash doesn’t really know about integers or other numeric types. Right?

Not really. You can “declare” an integer variable like this:

declare -i foo

This makes foo into an integer type variable! Here’s a more concrete example, showing what an integer type actually does:

# declare our variable as an integer type
declare -i foo

# assign 2 to foo and print it
foo=2
echo $foo              # prints 2

# what happens when we assign a string?
foo="hello, world"
echo $foo              # prints 0!

As you can see, once foo is declared as an integer variable it can no longer be coerced to a string type. There are other nifty things you can do with declare, such as the usage of declare -r for “readonly” variables. And more options are in the manual!

Bash scripting is notoriously difficult to get right. If you take the time to use the declare feature it can help you keep your Bash scripts readable and correct.