To export variables in a Bash shell, you use the export command. This makes the variable available to child processes, allowing them to access the variable's value. Here's how to do it:
Steps to Export Variables
-
Define a Variable:
First, create a variable without exporting it:MY_VAR="Hello, World!" -
Export the Variable:
Use theexportcommand to make the variable available to child processes:export MY_VARAlternatively, you can define and export a variable in one line:
export MY_VAR="Hello, World!" -
Access the Exported Variable:
You can access the exported variable in the current shell or any child processes:echo $MY_VAR -
Using in a Child Process:
To demonstrate that the variable is available in a child process, you can run a subshell:bash -c 'echo "MY_VAR in child process: $MY_VAR"'
Example Script
Here’s a complete example in a script:
#!/bin/bash
# Define and export a variable
export MY_VAR="Hello, World!"
# Access the variable in the current shell
echo "In current shell: $MY_VAR"
# Access the variable in a child process
bash -c 'echo "In child process: $MY_VAR"'
Summary
- Use
export VARIABLE_NAMEto make a variable available to child processes. - You can also define and export a variable in one command.
- Remember that exported variables are not available in other separate shell sessions unless defined in a startup file (like
.bashrcor.zshrc).
If you have any further questions or need more examples, feel free to ask!
