In this section, we will explore how to use variables and constants in Bash scripting. Understanding these concepts is crucial for writing effective and efficient scripts.
What are Variables?
Variables in Bash are used to store data that can be referenced and manipulated throughout your script. They are essential for creating dynamic and flexible scripts.
Declaring Variables
To declare a variable in Bash, you simply assign a value to a name without any spaces around the =
sign.
Explanation
greeting="Hello, World!"
: This line declares a variable namedgreeting
and assigns it the value "Hello, World!".echo $greeting
: This line prints the value of thegreeting
variable to the terminal.
Variable Naming Rules
- Variable names must start with a letter or an underscore (
_
). - Variable names can contain letters, numbers, and underscores.
- Variable names are case-sensitive (
VAR
andvar
are different).
Example
#!/bin/bash # Valid variable names name="Alice" _age=25 city="New York" # Invalid variable names # 1name="Bob" # Starts with a number # user-name="Charlie" # Contains a hyphen echo "Name: $name" echo "Age: $_age" echo "City: $city"
Constants
In Bash, there is no built-in way to declare a constant (a variable whose value cannot be changed). However, you can achieve a similar effect by using the readonly
command.
Declaring Constants
#!/bin/bash # Declaring a constant readonly PI=3.14159 # Trying to change the value of the constant # PI=3.14 # This will cause an error echo "The value of PI is $PI"
Explanation
readonly PI=3.14159
: This line declares a constant namedPI
and assigns it the value 3.14159. Thereadonly
command ensures that the value ofPI
cannot be changed.PI=3.14
: This line is commented out because attempting to change the value of a constant will result in an error.
Practical Examples
Example 1: Simple Calculator
#!/bin/bash # Declaring variables num1=10 num2=5 # Performing arithmetic operations sum=$((num1 + num2)) difference=$((num1 - num2)) product=$((num1 * num2)) quotient=$((num1 / num2)) # Displaying the results echo "Sum: $sum" echo "Difference: $difference" echo "Product: $product" echo "Quotient: $quotient"
Explanation
num1=10
andnum2=5
: These lines declare two variables,num1
andnum2
, and assign them values.sum=$((num1 + num2))
: This line calculates the sum ofnum1
andnum2
and assigns the result to thesum
variable.- The other arithmetic operations follow a similar pattern.
Example 2: Using Constants
#!/bin/bash # Declaring constants readonly TAX_RATE=0.07 price=100 # Calculating the total price including tax total_price=$(echo "$price + ($price * $TAX_RATE)" | bc) # Displaying the total price echo "Total Price: $total_price"
Explanation
readonly TAX_RATE=0.07
: This line declares a constant namedTAX_RATE
and assigns it the value 0.07.total_price=$(echo "$price + ($price * $TAX_RATE)" | bc)
: This line calculates the total price including tax using thebc
command for floating-point arithmetic.
Exercises
Exercise 1: Temperature Conversion
Write a script that converts a temperature from Celsius to Fahrenheit. The formula for conversion is F = C * 9/5 + 32
.
Solution
#!/bin/bash # Declaring a variable for Celsius temperature celsius=25 # Converting Celsius to Fahrenheit fahrenheit=$((celsius * 9 / 5 + 32)) # Displaying the result echo "$celsius°C is equal to $fahrenheit°F"
Exercise 2: Area of a Circle
Write a script that calculates the area of a circle given its radius. Use the constant PI=3.14159
.
Solution
#!/bin/bash # Declaring a constant for PI readonly PI=3.14159 # Declaring a variable for the radius radius=5 # Calculating the area of the circle area=$(echo "$PI * $radius * $radius" | bc) # Displaying the result echo "The area of a circle with radius $radius is $area"
Common Mistakes and Tips
- Forgetting the
$
sign: Always use the$
sign to reference a variable's value. - Using spaces around
=
: Do not use spaces around the=
sign when assigning values to variables. - Changing constants: Remember that constants declared with
readonly
cannot be changed.
Conclusion
In this section, we covered the basics of variables and constants in Bash. You learned how to declare and use variables, the rules for naming them, and how to create constants using the readonly
command. We also provided practical examples and exercises to reinforce these concepts. In the next section, we will delve into basic operators in Bash scripting.
Bash Programming Course
Module 1: Introduction to Bash
Module 2: Basic Bash Commands
- File and Directory Operations
- Text Processing Commands
- File Permissions and Ownership
- Redirection and Piping