Search code examples
bashshellgit-bashminttygit-for-windows

Can I set an environment variable on Bash's command line?


I am trying to set an environment variable for Bash. However, I need this to be set before any of the shell's startup scripts (including /etc/profile), because /etc/profile acts differently based on the value of this variable.

Specifically, I want to create a shortcut to MinTTy that works like git-bash, but I need to set the MSYSTEM environment variable before the shell starts, or at least before it starts processing any startup scripts.

A solution that has MinTTy setting the environment variable before it starts the shell will also be accepted.

Edit: What I am really looking for is sort of a command-line option to BASH that will set an environment variable, somewhat akin to the -D option to most C (and other) compilers. This would be a "general case" solution. Alternatively, a similar option (command line or configuration) to MinTTy will also do the job.

For my specific need, I have an idea for a potential work-around: Run a BASH script - with no startup scripts - that sets my required variable and execs another shell as a login shell.


Solution

  • Define the target of your shortcut file as follows:

    C:\cygwin64\bin\mintty.exe /bin/bash -l -c "MSYSTEM=MINGW64 exec -l bash"
    

    This command:

    • invokes bash directly as a login shell (-l)
    • passes it a command (-c) that defines the environment variable of interest (MSYSTEM=MINGW64) and then invokes a new copy of bash (exec -l bash), which inherits the existing environment, plus the new definition, but sources the profile(s) again, due to -l
      (and prepends - to the executable name reported in $0 (-bash), as would happen if you started Mintty with just -, which is what the regular Cygwin64 Terminal shortcut does).

    An alternative is to set the environment variable in Windows first.

    • [Not an option for the OP] If the environment variable should always have the same value, set it persistently as follows: run sysdm.cpl, go to the Advanced tab, click on Environment Variables... and define variable MSYSTEM as needed.

    • To define the variable ad-hoc, create a batch file as follows and make the shortcut target that 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 the batch file from a shortcut briefly opens a regular console window before opening Mintty, which may be undesired.

    A simple helper WSH script, as demonstrated in this answer of mine, can prevent this.