Friday 15 May 2015

export command in linux



The export command marks an environment variable to be exported with any newly created child  processes (also to new shell script file) and thus it allows a child process to inherit all exported variables.

Optons
  • -p    -------------->   List of all names that are exported in the current shell
  • -n    -------------->   Remove names from export list
  • -f     -------------->   Names are exported as functions

Simple example given bellow:

  • Line 1: new variable called "a" is created to contain string "linuxuser"
  • Line 2: we use echo command to print out a content of the variable "a"
  • Line 3: we have created a new child bash shell
  • Line 4: variable "a" no longer have any values defined


From the above we can see that any new child process created from a parent process by default does not inherit parent's variables. For accessing the variable in parent shell we can use "export" command.

Simple example given bellow:


On the line 3 we have now used the export command to make the variable "a" to be exported when a new child process is created. As a result the variable "a" still contains the string "linuxuser" even after a new bash shell was created. It is important to note that, in order to export the variable "a"  to be available in the new process, the process must be created from the parent process where the actual variable was exported.

Child vs Parent process

Any process can be a parent and child process at the same time. The only exception is the init process, which is always marked with PID ( process ID ) 1. Therefore, init is a parent of all processes running on your Linux system.



Any process created will normally have a parent process from which it was created and will be considered as a child of this parent process


  • Line 1: print a PID for a current shell - 27861
  • Line 2: create a new child process from the process ID 27861
  • Line 3: print a PID for a current shell - 28034
  • Line 4: with use of the ps command print the child process of PID 27861

When creating a new child process an export command simply ensures that any exported variables in the parent process are available in the child process.


Using the option -p we can show all the export variable in the system


As shown previously, to export a variable we simply use the  variable's name as an argument to an export command.


With the option -f the export command can also be used to export functions. In the example below, we will create a new bash function called printos


No comments:

Post a Comment