How to specify environment variable for a command on Linux

Sometime we need to run a command with specific environment variables. These can be either just needed for the command or for the whole bash shell. Here are some ways to specify env variable for a command on Linux bash shell:

Specify env variable as part of same command

Prefix key=value before the command. Multiple pairs can also be specified using space delimiter. This will not work if we run multiple commands joined by pipes. Env variable is applicable to only first command. Here is an example:

$ LC_ALL=C sort file1.txt

Specify env variable as shell variable

Set it as environment variable for the current shell. This will continue to work for any command in current shell. e.g.

$ LC_ALL=C; tail file1.txt | sort

Specify env variable as exported shell variable

In case we want the variable to be available in child shells, we can prefix it with export as shown below:

// Without export
$ unset FOO; FOO=111; bash -c 'echo FOO_from_env=$FOO'
FOO_from_env=

// With export
$ unset FOO; export FOO=111; bash -c 'echo FOO_from_env=$FOO'
FOO_from_env=111
Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments