The declare command in Bash is used to define, modify, and display variables and functions. In Bash Scripting, the primary purpose of declare
command is to set attributes for Variables and Functions and display their current state.
In this tutorial, we will learn how to use the declare
command in Bash scripts with examples on Linux.
Table of Contents
1. Basic Usage of declare Command in Bash
1.1. Define a Variable
The declare
command is often used to define variables with specific attributes.
declare my_var="Hello, World!" echo "$my_var"
This works the same as a normal variable assignment (my_var="Hello, World!"
).
1.2. Make a Variable Uppercase
declare -u upper_var="hello world" echo "$upper_var" # Outputs "HELLO WORLD"
The -u
flag converts the value of upper_var
to uppercase.
1.3. Make a Variable Lowercase
declare -l lower_var="HELLO WORLD" echo "$lower_var" # Outputs "hello world"
The -l
flag converts the value of lower_var
to lowercase.
2. Listing Variables and their Values
2.1. List All Variables
declare -p
This shows all variables and their values.
2.2. List a Specific Variable
declare -p my_var
Output:
declare -- my_var="Hello, World!"
The declare --
means it’s a regular variable without special attributes.
3. Special Attributes with declare
3.1. Make a Variable Read-Only (-r
)
Set a Read-Only Variable:
declare -r readonly_var="Fixed Value" readonly_var="New Value" # This will cause an error
The -r
flag makes readonly_var
read-only. Attempting to change it will result in an error. Once set, it cannot be changed.
3.2. Force a Variable to Be an Integer (-i
)
Bash will treat the variable as a number and do calculations automatically.
declare -i num=10 num+=5 echo "$num" # Output: 15
The -i
flag makes num
an integer. If you assign a non-integer value, it will default to 0
.
If you try to assign a non-numeric value, it will be ignored:
num="hello" echo "$num" # It will display 0.
3.3. Set a Variable as an Indexed Array
declare -a my_array=("apple" "banana" "cherry")
The -a
flag makes my_array
an indexed array.
To print the whole array, you can use:
echo "${my_array[@]}"
Sample Output:
apple banana cherry
To access individual elements from the array:
echo "${my_array[0]}" # Output: apple echo "${my_array[1]}" # Output: banana echo "${my_array[2]}" # Output: cherry
Looping Through the Array:
for item in "${my_array[@]}"; do echo "$item" done
Getting the Length of the Array:
echo "${#my_array[@]}" # Output: 3
Adding a New Element:
my_array+=("date") echo "${my_array[@]}" # Output: apple banana cherry date
Removing an Element:
To remove the second element (banana
at index 1
):
unset my_array[1] echo "${my_array[@]}" # Output: apple cherry date
3.4. Set a Variable as an Associative Array (Bash 4+)
declare -A my_assoc_array=([fruit]="apple" [color]="red")
This creates an associative array (also called a dictionary or hash map) in Bash, where keys (instead of numeric indexes) map to specific values.
The -A
flag makes my_assoc_array
an associative array (key-value pairs).
Accessing Elements:
echo "${my_assoc_array[fruit]}" # Output: apple echo "${my_assoc_array[color]}" # Output: red
Printing All Keys:
echo "${!my_assoc_array[@]}" # Output: fruit color
Printing All Values:
echo "${my_assoc_array[@]}" # Output: apple red
Looping Through the Array:
for key in "${!my_assoc_array[@]}"; do echo "$key => ${my_assoc_array[$key]}" done
Output:
fruit => apple color => red
Adding a New Key-Value Pair:
my_assoc_array[shape]="circle" echo "${!my_assoc_array[@]}" # Output: fruit color shape echo "${my_assoc_array[shape]}" # Output: circle
Removing a Key
unset my_assoc_array[color] echo "${!my_assoc_array[@]}" # Output: fruit shape
Checking If a Key Exists:
if [[ -v my_assoc_array[fruit] ]]; then echo "Key 'fruit' exists!" fi
Output:
Key 'fruit' exists!
3.5. Export a Variable to Subshells (-x
)
This makes a variable available to child processes.
declare -x my_env_var="Exported Value"
This command creates an environment variable (my_env_var
) and makes it available to child processes (like a new Bash shell).
bash -c 'echo "$my_env_var"' # Output: Exported Value
What Happens If We Don't Use declare -x
?
my_env_var="Not Exported" bash -c 'echo "$my_env_var"'
You will see an empty output.
Without -x
, the variable exists only in the current shell and is not passed to child processes.
Alternatively, we can use export
instead of declare -x
.
export my_env_var="Exported Value"
Both declare -x
and export
make variables available to subshells.
4. Managing Functions with declare
4.1. Setting Attributes for Functions
As I already mentioned, the declare
command allows you to set various attributes for variables and functions. For example, to make a Variable Local to a Function:
my_function() { declare -l local_var="This is local" echo "$local_var" }
The -l
flag makes local_var
local to the function.
If you call the function:
my_function
The output will be:
this is local
Even though "This is local"
has uppercase letters, declare -l
forces all characters to lowercase.
4.2. List All Functions (-f
)
declare -f
This shows all defined functions along with their contents.
4.3. List Only Function Names (-F
)
declare -F
This shows just the function names without their definitions.
4.4. Export a Function
declare -xf my_function
The -xf
flag makes my_function
available to child processes (e.g., scripts or subshells).
5. Check if a Variable or Function Exists
The declare
command can also be used to verify if a variable or function exists:
if declare -p variable_name &>/dev/null; then echo "Variable exists" fi
Replace variable_name
with the actual name.
6. Remove Attributes
Remember we use -i
when we declare a variable. We can use +
instead of -
to remove an attribute. For example:
declare +i num # Removes the integer attribute from `num`.
You can now assign other attribute (E.g. a string) without any errors:
num=hello
To verify it, print the variable value:
echo $num
It should output hello
.
Please note that declare +i num
removes the integer attribute but does not unset or delete the variable.
7. Unsetting Variables and Functions
We can remove variables or functions using unset
command.
To remove a variable:
unset my_var
To remove a function:
unset -f function_name
Example: Combining Variable and Function Management
The following example shows how declare
can be used for both variables and functions:
# Declare an integer variable declare -i num=10 # Declare a read-only variable declare -r readonly_var="This cannot be changed" # Declare a function my_function() { declare -l local_var="This is local" echo "$local_var" } # List all functions declare -F # View the definition of my_function declare -f my_function
Summary of declare
Options
Option | Purpose |
---|---|
-a | Declare an indexed array. |
-A | Declare an associative array (Bash 4+). |
-i | Declare an integer variable. |
-r | Declare a read-only variable or function. |
-x | Export the variable or function to the environment. |
-f | Display the definition of a function. |
-F | Display the names of all functions. |
-l | Convert the value to lowercase (for variables). |
-u | Convert the value to uppercase (for variables). |
-p | Display the attributes and value of a variable. |
Conclusion
The declare
command is one of the useful commands in advanced Bash scripting. It is primarily used to:
- Define and manage variables with specific attributes (e.g., integers, arrays, read-only),
- Define and manage functions (e.g., list, view, or export them),
- Set or remove attributes for variables and functions.
Hope this helps.