Is it possible to set an environment variable on the bash command line?
I am trying to set an environment variable for Bash. However, I need this to be set before any shell startup script (including /etc/profile
), because it /etc/profile
acts differently depending on the value of this variable.
Specifically, I want to create a shortcut for MinTTy that works like git-bash
, but I need to set an environment variable MSYSTEM
before the shell starts, or at least before it starts processing any startup scripts.
A decision will also be made in which MinTTy sets an environment variable before it starts the shell.
Edit:
What I'm really looking for is a command line option for BASH that will set an environment variable somewhat similar to the option -D
on most C (and others) compilers. This will be the "general case". Alternatively, a similar option (command line or config) for MinTTy will do the job as well.
For my specific need, I have an idea for a potential job: run a BASH script - no startup scripts - that sets my required variable and exec
another shell as the login shell.
source to share
Define the purpose of your shortcut file as follows:
C:\cygwin64\bin\mintty.exe /bin/bash -l -c "MSYSTEM=MINGW64 exec -l bash"
This command:
- calls
bash
directly as login shell (-l
) - passes it the command (
-c
), which defines the environment variable of interest (MSYSTEM=MINGW64
), and then calls a new copybash
(exec -l bash
), which inherits the existing environment, plus the new definition, but returns the profile again due to-l
(and appends-
to the executable name given in$0
(-bash
), as it happened if you started Mintty with just-
, which is what the regularCygwin64 Terminal
shortcut does ).
An alternative is to set the environment variable on Windows first.
-
[Not an option for the OP] If the environment variable should always have the same value, set it aggressively like this: run
sysdm.cpl
, go to tabAdvanced
, clickEnvironment Variables...
and define the variableMSYSTEM
as needed. -
To define an ad-hoc variable, create a batch file as follows and make a shortcut target for the batch file:
@echo off # Define the env. variable with the desired value. set "MSYSTEM=MINGW64" # Invoke Mintty with a login shell, which will now see the env. variable. # Adjust the path to mintty.exe as needed. c:\cygwin64\bin\mintty.exe -
Note. Opening a batch file from a shortcut briefly opens a regular console window before opening Mintty, which may not be desirable.
A simple WSH script helper as shown in this answer can prevent this.
source to share
While I have already accepted the answer above, I found this link which specifically addresses the second part of my question (Mintty specific) or an alternative way to set an environment variable before running the command.
The contents of a Windows shortcut can be:
C:\cygwin64\bin\mintty.exe -t "Title" /bin/env "MSYSTEM=MINGW64" /bin/bash -l
(Suggested Mintty Tips : Setting Environment Variables .)
source to share