Bash Variables



Bash Variables

In Bash scripting, variables are used to store data that can be referenced and manipulated throughout your script. Variables make it easy to manage and reuse data.


Syntax

Variables in Bash are defined by assigning a value to a variable name without spaces around the equal sign.

variable_name=value

To reference a variable, use the $ symbol followed by the variable name.

echo $variable_name

Example Bash Variables

Let's look at some examples of how to use variables in Bash:

1. Define and Use a Variable

This script defines a variable and prints its value.

#!/bin/bash

# Define a variable
message="Hello, World!"

# Print the variable's value
echo $message

In this script, the variable message is defined with the value 'Hello, World!'. The echo command is used to print the value of the variable.

Define and use a variable in Bash

2. Define and Use Numeric Variables

This script defines numeric variables, performs arithmetic operations, and prints the results.

#!/bin/bash

# Define numeric variables
num1=5
num2=10

# Perform arithmetic operations
sum=$((num1 + num2))
difference=$((num1 - num2))
product=$((num1 * num2))
quotient=$((num1 / num2))

# Print the results
echo "Sum: $sum"
echo "Difference: $difference"
echo "Product: $product"
echo "Quotient: $quotient"

In this script, the variables num1 and num2 are defined with numeric values. Arithmetic operations are performed using the $(( ... )) syntax, and the results are printed using the echo command.

Define and use numeric variables in Bash

3. Use Command Substitution to Assign Variable

This script uses command substitution to assign the output of a command to a variable and prints the variable's value.

#!/bin/bash

# Use command substitution to assign a variable
current_date=$(date)

# Print the variable's value
echo "Current date and time: $current_date"

In this script, the variable current_date is assigned the output of the date command using the $( ... ) syntax. The echo command is used to print the value of the variable.

Use command substitution to assign variable in Bash

Conclusion

Using variables in Bash is fundamental for storing and manipulating data in shell scripts. Understanding how to define, use, perform arithmetic operations on, use command substitution with, and export variables can help you write more effective and flexible Bash scripts.