Skip to content

Variables#

After the shebang we have a variable. It's called yourname and it contains the value of another variable called $1.

The concept of a variable can be compared to a box. Let's illustrate this:

A variable in programming

A variable in programming
(Pluke, CC0, via Wikimedia Commons)

We can see the values "Dog" and "Cat" being stored in "boxes", which are memory addresses. Memory is split up into "segments" that represent a certain "block" of information. If you store a large file in memory, then it's very likely it'll be spread across multiple blocks.

Here the value "Dog" is being stored at (fictional) address 0. The "Cat" variable can be found at 2.

So basically, a variable is some value being stored at some location in memory. We use a variable to recall that value later on by only remembering and using the name of the variable. Without this kind of functionality, you'd have to access the value via its memory address. That would be a nightmare given how big 64-bit memory addresses are, and how many addresses there are, not to mention many other factors.

Storing a value#

In bash, we store a value like this: variable_name=value. The name of the variable is how you'll use it throughout your script. The value can be a whole variety of things from a simple string like "hello" to calling an external program and storing its STDOUT, like variable_name=$(ls -l).

We won't go into detail with regards to what constitutes all the available options for composing a variable. What you need to understand right now is what a variable looks like, what it's used for, and how it's used.

In our script, we've given the variable named yourname the value $1, which is actually another variable! I've done this on purpose to demonstrate both defining a variable and using one in a single take.

The $1 variable is a special variable that contains the first argument passed to the script when you run it. So if you run it like: ./simple_script Mike then yourname="Mike". If you omit the value, then yourname= (empty string).

Question: what happens if you use $0 instead? Try it and see.

Using the value#

We can use that variable in our script in various ways. There are loads of ways we can use the variable, actually. A concept known as Shell Parameter Expansion is a powerful way to use variables, and their values, in complex ways.

For the sake of keeping things simple, we're using our yourname variable inside of a string:

1
echo "... ${yourname}"

The ${} syntax is used to "embed" a variable inside of a string, and is replaced with the contents of the variable itself.

We can see a different way to use a variable in the script:

1
yourname=$1

What we're actually doing here is assigning the value of $1 to the variable yourname, as we discussed above.

At this point, you know enough about variables and should be able to read a simple bash/shell script and determine where the variables/values are being defined and used.