export – Set the export attribute for a shell variable or function

The export command is a built-in command in Linux. It is used to set the export attribute for a shell variable or function. When a variable or function is exported, it becomes available to any child processes that are spawned from the current shell. This can be useful when you need to pass variables or functions to child processes, such as when running scripts or programs that require certain environment variables to be set.

Overview

The syntax of the export command is as follows:

export [option] [name[=value]]

Here, option is an optional argument that can be used to modify the behavior of the command. name is the name of the variable or function you want to export, and value is the value you want to assign to the variable (if it is a variable) or the body of the function (if it is a function).

To export a variable, you simply need to use the export command followed by the name of the variable. For example:

export MY_VAR

This will export the variable MY_VAR to any child processes that are spawned from the current shell.

To export a function, you need to use the export command followed by the name of the function and its body. For example:

export -f my_function

This will export the function my_function to any child processes that are spawned from the current shell.

Options

The following table lists the available options for the export command:

Option Description
-f Export the function named following the -f option.
-n Remove the export attribute from the variable named following the -n option.
-p Display the names and values of all exported variables.

Troubleshooting tips

  • If you are having trouble exporting a variable or function, make sure that it is defined in the current shell. Variables and functions that are defined in a subshell or a script will not be available for export.
  • If you are trying to export a variable that contains spaces or special characters, you may need to enclose it in quotes to prevent the shell from interpreting the characters as special operators. For example:
export "MY VAR"

Notes

  • When you export a variable or function, it becomes available to any child processes that are spawned from the current shell. However, it will not be available to the parent shell or any other processes that are not direct children of the current shell.
  • If you want to make a variable or function available to all processes on the system, you can add it to the system-wide environment file, which is usually located at /etc/environment or /etc/profile.
  • If you want to make a variable or function available to all processes that are started by a particular user, you can add it to the user’s shell initialization file, which is usually located at ~/.bashrc or ~/.bash_profile.