To define and use variables in Bash scripts, follow these steps:
Variable Naming: Choose a name for your variable starting with a letter or underscore (_) followed by any combination of letters, digits, or underscores. Variable names are case-sensitive.
Variable Assignment: Use the following syntax to assign a value to a variable:
variable_name=value
Avoid using spaces around the equals sign (=).
Using Variables: To use the value stored in a variable, precede the variable name with a dollar sign ($). For example, if you have a variable named "name", you can use it like this:
echo $name
Accessing Variables Within Strings: To include the value of a variable within a string, use double quotes ("") instead of single quotes (''). For example:
message="Hello, $name"
echo $message
The output will be "Hello, [value of name variable]”.
Special Variables: Bash provides a set of predefined variables that store information like script name, command-line arguments, etc. Some commonly used special variables are:
Here's an example Bash script using variables:
#!/bin/bash
name="John Doe"
age=30
echo "Name: $name"
echo "Age: $age"
echo "Script Name: $0"
echo "First Argument: $1"
echo "All Arguments: $@"
echo "Total Arguments: $#"
echo "Exit Status: $?"
Save the script to a file (e.g., script.sh
), make it executable (chmod +x script.sh
), and then run it with command-line arguments:
./script.sh argument1 argument2
The script will display the values of the variables and the provided command-line arguments.