In Bash, variables are used to store and manipulate data. They allow you to store values, such as text strings or numbers, and use those values throughout your script. Variables in Bash are untyped, meaning they can hold values of any type.
Here’s an example of defining and using variables in Bash:
name="John"
age=25
echo "My name is $name and I am $age years old."
In this example, we define two variables: name
and age
. The name
variable holds the string “John”, and the age
variable holds the number 25. We then use the variables within the echo
command by enclosing them in double quotes and preceding them with a dollar sign $
. This allows the values of the variables to be substituted into the string.
When the script is executed, it will output: “My name is John and I am 25 years old.”
Some key points about Bash variables:
- Variable names are case-sensitive and can contain letters, numbers, and underscores.
- Conventionally, variable names are written in lowercase.
- There should be no spaces around the equal sign (=) when assigning values to variables.
- To access the value of a variable, you need to prefix the variable name with a dollar sign ($).
- Variables can be assigned values from command output using command substitution. For example:
current_date=$(date +%Y-%m-%d)
echo "Today is $current_date."
- In this example, the
current_date
variable is assigned the current date using thedate
command with the%Y-%m-%d
format. - You can modify the value of a variable by assigning a new value to it. For example:
name="Alice"
echo "Hello, $name!"
name="Bob"
echo "Hello again, $name!"
In this example, the value of the name
variable is changed from “Alice” to “Bob” before the second echo
command.
Bash variables are a fundamental concept for storing and manipulating data within scripts. They provide flexibility and allow scripts to adapt dynamically to different situations.