Bash Scripting for Beginners [Part 3] - Variables

Bash Scripting for Beginners [Part 3] - Variables

After exploring Linux Environment Variables in Part 2, in this edition we are going to focus on using variables in Bash scripts.

In the Bash variables are untyped, e.g. unlike other programming languages we don't use types to define them. Still internally we have some type of segregation between variable values.

Defining a variable in a script file is working exactly as defining an local Environment Variable.

#!/usr/bin/env bash

number=42

echo "Value of number: $number"
01_variables.sh

Once we saved the script to a file, we can run it by either using the interpreter directly with bash 01_variables.sh or by making it executable with chmod u+x 01_variables.sh and using ./01_variables.sh.

Check the first part of this tutorial to learn more about executing bash scripts.

Variables defined in bash scripts are generally written lower-case by convention to differentiate them from Environment Variables, which are written upper-case. As executing a shell script creates a new instance of the shell (bash in this case), the variables lifespan, even with export, ends with the termination of the script.

Working with Variables

Assigning a variable is done without the dollar sign ($), accessing it's value requires it. Don't use spaces before and after the equal sign.

#!/usr/bin/env bash

a=42
b=a

# Prints "a"
echo "$b"

b=$a

# Prints 42
echo "$b"
02_multiple_variables.sh

As you can see b=a assigns b the String value of "a" and not 42. In order to access the value of a, you need to put the dollar sign (return) in front of the variable name.

#!/usr/bin/env bash

name="bytee"

echo "Hello $name"

# This is still working, as the dot is not allowed as variable name.
echo "$name.net"

# This will output an empty line, as the interpreter is looking for a variable called `namenet`.
echo "$namenet"

# We have to use curly braces after the dollar sign to delimit the variable name.
echo "${name}net"
03_delimit.sh

To delimit the variable name, use curly braces.

Assignment using let
#!/usr/bin/env bash

a=20
b=22
c="$a + $b"

# Prints "20 + 22"
echo "$c"

let c=$a+$b

# Prints "42"
echo "$c"
04_let.sh

let evaluates the expression, instead of just printing the text. As an alternative you can use an arithmetic expression, as show in (part 4)[] of this tutorial.

The equal sign (=) can be either an assignment or comparison operator depending on the context.

Untyped variables allow for more flexibility, but come with certain disadvantages too. Check the next part on how to calculate in the Bash for more on this topic.