Bash Script Variables: Simple Guide
Introduction
If you’ve ever done a bit of programming before, you’ve probably heard about variables. If not, think of them as little containers where we can put information temporarily. In Bash scripting, these variables are super handy for controlling what our script does. We’ll learn different ways to set up variables and how to use them effectively.
Variables might seem easy at first, but they can get tricky if you’re not careful. So, in this section, we’ll break down how they work. Don’t worry if it feels like a lot to take in — understanding it now will make things much easier as we dive into more complicated scripts later on.
How do they Work?
A variable is like a temporary storage unit for information. There are two main things we do with variables:
- Setting a value: This means putting some information into the variable.
- Reading the value: This means checking what's stored in the variable.
Variables can get their value in a few different ways. The most common ways are:
- We directly tell the variable what value to hold.
- The value comes from the result of running a command or program.
To read a variable, we just need to use its name with a dollar sign ($) in front of it. Before Bash runs each line of our script, it checks if there are any variables. If it finds any, it swaps out the variable names with their values, then runs the line.
Here are some basic rules about using variables:
- When you're using or reading a variable, always put a dollar sign ($) before its name.
- When you're setting a variable, don't use the dollar sign ($).
- Some folks like to write variable names in all uppercase so they're easy to spot, but it's up to you. You can use uppercase, lowercase, or even a mix.
- You can put a variable anywhere in your script, and Bash will replace it with its value when it runs the script. This happens before the command actually runs, so the right value gets used.
A Simple “Hello World” Example
#!/bin/sh
MY_MESSAGE="Hello World"
echo $MY_MESSAGE
Sure, here’s a simplified version of the text:
To illustrate the use of variables, let’s revisit our initial “Hello World” example. Although it’s a straightforward illustration, we can still employ variables.
Remember, when assigning values to variables in shell scripting, there shouldn’t be any spaces around the “=” sign. For instance, `VAR=value` is valid, while `VAR = value` isn’t. In the former case, the shell recognizes the “=” symbol as a variable assignment. However, in the latter case, the shell interprets “VAR” as a command to execute, leading to errors.
This behavior is logical. How else would the shell know to execute a command named “VAR” with “=” as the first argument and “value” as the second?
Now, let’s input the following code into a file named hello.sh:
More Explanation
In the above code, we’re assigning the string “Hello World” to a variable named MY_MESSAGE, and then we’re displaying the value of that variable using the echo command.
It’s important to note that we enclose the string “Hello World” in quotes when assigning it to the variable. Unlike the echo command, which can handle multiple parameters, a variable can only hold one value. Therefore, if we don’t use quotes, the shell might interpret “World” as a separate command after assigning MY_MESSAGE=Hello.
Variables in shell scripting aren’t type-specific; they can store strings, integers, real numbers, or any other data type without distinction.
For those familiar with Perl, this behavior might seem natural, but for those accustomed to languages like C, Pascal, or Ada, it might appear unusual. Under the hood, everything is stored as strings, but functions designed to handle numbers can treat them accordingly.
Attempting to perform arithmetic operations on variables containing strings will result in errors.
Handling Variable Types and Interaction in Bash
Handling Variable Types and Interaction in Bash
When dealing with variables in Bash, it’s essential to understand how different types are handled and how interactions can vary based on their content. Consider the following script, which illustrates various variable assignments and interactions:
#!/bin/bash
# Assigning variables of different types
MY_MESSAGE="Hello World"
MY_SHORT_MESSAGE=hi
MY_NUMBER=1
MY_PI=3.142
MY_OTHER_PI="3.142"
MY_MIXED=123abc# Attempting arithmetic operation on non-numeric variable
x="hello"
expr $x + 1 # This will result in an error# Interactive variable assignment using the read command
echo "What's your name?"
read name
echo "Hello, $name! Nice to meet you."
Before talking about the above Script, let’s discuss what ‘expr’ is, as it’s essential.
The expr
command in Unix-like operating systems is a utility used for evaluating expressions. It primarily performs arithmetic operations and string comparisons. Here's a breakdown of its functionalities:
- Arithmetic Operations:
expr
can perform basic arithmetic operations such as addition, subtraction, multiplication, and division.- Example:
expr 10 + 5
will output15
.
2.String Comparisons:
expr
can compare strings, returning an exit status of 0 if the strings are equal and 1 if they are not.- Example:
expr "hello" = "world"
will return 1(false).
3.Substrings and Length:
- It can extract substrings from a string and determine the length of a string.
- Example:
expr substr "hello world" 1 5
will outputhello
, andexpr length "hello"
will output5
.
4.Pattern Matching:
expr
can perform pattern matching using regular expressions.- Example:
expr "hello world" : '.*'
will output11
, indicating the length of the string.
5.Logical Operations:
- It can perform logical operations such as AND (
&
), OR (|
), and NOT (!
), although the syntax for these operations can be complex. - Example:
expr 1 \& 0
will output0
.
However, it’s essential to note that
expr
has limitations:
- It only works with integer arithmetic; it doesn’t handle floating-point numbers.
- It’s an external command, so using it frequently can affect script performance compared to using built-in shell arithmetic.
- Its syntax can be cumbersome and prone to errors, especially for complex expressions.
Due to these limitations, in modern Bash scripting, the use of built-in arithmetic operations ($((...))
), command substitution with arithmetic expressions, or external utilities like bc
(for floating-point arithmetic) are often preferred over expr
.
Now let’s talk about the script
In the above script:
- We assign various types of values to different variables, including strings, integers, and floating-point numbers.
- An attempt is made to perform an arithmetic operation (
expr $x + 1
) on a non-numeric variablex
, resulting in an error due toexpr
expecting numeric arguments only. - The script then interacts with the user by using the
read
command to input a value for the variablename
, and then greets the user personally.
It’s crucial to remember that while Bash allows flexibility in variable assignments, proper handling of variable types is necessary to avoid unexpected errors or behavior. Additionally, when interacting with users, utilizing commands like read
enables dynamic input, enhancing script interactivity.
Scope of Variables
In Bourne shell scripting, variables don’t need to be explicitly declared before use, unlike in languages such as C. However, if you attempt to read the value of an undeclared variable, it will result in an empty string without generating any warnings or errors. This behavior can lead to subtle bugs in scripts.
For instance, consider the following scenario:
MY_FIRST_VARIABLE=Hello
echo $MY_FIRST_VAIABLE
In the second line, there’s a typo (VAIABLE instead of VARIABLE) when attempting to echo the value of the variable. As a result, nothing will be printed because the variable MY_FIRST_VAIABLE is not declared, and hence its value is an empty string.
To avoid such issues, it’s essential to pay attention to variable names and ensure they are spelled correctly when referencing them.
Assignment Read about Export Command
Conclusion
In summary, understanding variables in Bash scripting is important for making scripts work well. Variables act like containers for information, helping scripts do things in a flexible way. In this guide, we learned how to set up variables and use them correctly.
We saw that variables can hold different types of information, like words, numbers, or decimals. We also learned that there are rules to follow when naming variables and using them in scripts.
We discussed how to do simple math with variables and interact with users by asking for input. We also talked about making sure to spell variable names correctly to avoid mistakes.
By learning about variables in Bash scripting, we can write scripts that do what we want them to do in a smoother way.
DAY-1 Blog
DAY-2 Blog