Before clarification
The POSIX shells (bash
, ksh
, etc) and the Bourne shell allow you to set environment variables on a command line for one command only:
MYTOOL_CONTEXT=<context> mytool do-stuff
This sets MYTOOL_CONTEXT
as an environment variable for that invocation of mytool
(only). Incidentally, most shells accept an option -k
(which is not standardized by POSIX) that means all arguments that look like VAR=value are treated as environment variables, even when they appear after the command name. This is a curiosity with rather limited practical value, which is why it is not standardized.
The POSIX env
command is designed to allow you to control the environment of an invoked command, though it is commonly used without any arguments to list the current environment. So, alternatively, you might use:
env MYTOOL_CONTEXT=<context> mytool do-stuff
The advantage of env
is that you can do things like unset every environment variable before setting the ones specified in the command line (so you get total control over the environment).
After clarification
If the intention is to set the environment for subsequent use, then the .
command is the one to use. You can create a file, context
, which contains commands to be executed to set the environment. Then you can use:
. context
and the contents of the file will executed in the context of the current shell, so you can set environment variables, etc. Bash provides a synonym, source
, for the .
command. It was inspired by the C shell which does not provide the .
command but does provide source
as an equivalent. The file named as an argument to the .
command will be searched for on $PATH
but does not need to be executable (readable is sufficient). If you provide extra arguments, they become the positional parameters ($1
, etc) for the duration of the .
command. Note too that any variables or functions created by the dotted file remain in effect when the file is finished (unlike variables in a normal script which vanish when the script completes). If you aren't going to pollute the user's name space, you have to be careful.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…