I am writing a shell script, to read a file which has key=value pair and set those variables as environment variables. But I have a doubt, if I do source file.txt
will that set the variables defined in that file as environment variable or I should read the file line by line and set it using export command ?
Is source command in this case different than export?
Export is a built-in command of the Bash shell. It is used to mark variables and functions to be passed to child processes. Basically, a variable will be included in child process environments without affecting other environments.
See help set : set is used to set shell attributes and positional attributes. Variables that are not exported are not inherited by child processes. export is used to mark a variable for export.
source is a shell built-in command which is used to read and execute the content of a file(generally set of commands), passed as an argument in the current shell script. The command after taking the content of the specified files passes it to the TCL interpreter as a text script which then gets executed.
In Linux systems, source is a built-in shell command that reads and executes the file content in the current shell. These files usually contain a list of commands delivered to the TCL interpreter to be read and run.
When you source
the file, the assignments will be set but the variables are not exported unless the allexport
option has been set. If you want all the variables to be exported, it is much simpler to use allexport
and source
the file than it is to read the file and use export
explicitly. In other words, you should do:
set -a . file.txt
(I prefer .
because it is more portable than source
, but source
works just fine in bash
.)
Note that exporting a variable does not make it an environment variable. It just makes it an environment variable in any subshell.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With