Difference Between export
and declare
in Bash
In Bash, both export
and declare
are used to manage variables, but they serve different purposes and have distinct functionalities. Understanding the differences between these two commands is essential for effective shell scripting and variable management.
1. Purpose of export
The export
command is used to set environment variables that are available to child processes. When you export a variable, it becomes part of the environment, allowing any subprocesses to access it.
Example of Using export
export MY_VAR="Hello, World!"
In this example:
- The variable
MY_VAR
is created and exported, making it available to any child processes.
Accessing an Exported Variable in a Child Process
bash -c 'echo $MY_VAR'
In this example:
- The command will output:
Hello, World!
becauseMY_VAR
has been exported.
2. Purpose of declare
The declare
command is used to create variables with specific attributes. It allows you to define the type of variable (e.g., integer, array) and set options such as readonly or export status. However, variables declared with declare
are not automatically exported to child processes unless explicitly done so.
Example of Using declare
declare -i MY_INT=10
In this example:
- The variable
MY_INT
is declared as an integer using the-i
option. - This means that any arithmetic operations performed on
MY_INT
will treat it as an integer.
Accessing a Declared Variable in a Child Process
bash -c 'echo $MY_INT'
In this example:
- The command will output nothing because
MY_INT
is not exported and is not available in the child process.
3. Key Differences
Here are the key differences between export
and declare
:
- Functionality:
export
makes a variable available to child processes, whiledeclare
is used to define variable attributes and types. - Exporting: Variables created with
declare
are not exported by default; you must useexport
separately to make them available to child processes. - Variable Types:
declare
allows you to specify variable types (e.g., integer, array), whileexport
does not.
4. Combining declare
and export
You can use both commands together to declare a variable and export it in one line:
declare MY_VAR="Hello, World!" && export MY_VAR
In this example:
- The variable
MY_VAR
is declared and then exported, making it available to child processes.
5. Conclusion
In summary, export
and declare
serve different purposes in Bash scripting. Use export
when you need to make a variable available to child processes, and use declare
when you want to define variable attributes or types. Understanding these differences will help you manage your variables more effectively in your scripts.