Changing .gitconfig location on Windows - windows

By default on Windows Git places global .gitconfig in c:\documents and settings\user\
How can I change that position so .gitconfig is stored in c:\my_configuration_files\?
Can it be done at all?

If you set HOME to c:\my_configuration_files\, then git will locate .gitconfig there. Editing environment variables is described here. You need to set the HOME variable, then re-open any cmd.exe window. Use the "set" command to verify that HOME indeed points to the right value.
Changing HOME will, of course, also affect other applications. However, from reading git's source code, that appears to be the only way to change the location of these files without the need to adjust the command line. You should also consider Stefan's response: you can set the GIT_CONFIG variable. However, to give it the effect you desire, you need to pass the --global flag to all git invocations (plus any local .git/config files are ignored).

Change HOME directory for this is wrong. Better is create symbolic link for gitconfig to HOME directory.
Move your .gitconfig from user home directory, to the directory where you want.
Run command line as Administrator
Go to your user home directory
Enter mklink .gitconfig \PathForNewLocationOfConfig.gitconfig

I have solved this problem using a slightly different approach that I have seen work for other configuration files. Git Config supports includes that allows you to point to a configuration file in another location. That alternate location is then imported and expanded in place as if it was part of .gitconfig file. So now I just have a single entry in .gitconfig:
[include]
path = c:\\path\\to\\my.config
Any updates written by Git to the .gitconfig file will not overwrite my include path. It does mean that occasionally I may need to move values from .gitconfig to my.config.

Look in the FILES and ENVIRONMENT section of git help config.

I'm no Git master, but from searching around the solution that worked easiest for me was to just go to C:\Program Files (x86)\Git\etc and open profile in a text editor.
There's an if statement on line 37 # Set up USER's home directory. I took out the if statement and put in the local directory that I wanted the gitconfig to be, then I just copied my existing gitconfig file (was on a network drive) to that location.

As of at least 2.34.1, you can now set GIT_CONFIG_GLOBAL environment variable to a path to your .gitconfig file. See http://git-scm.com/docs/git-config#_environment for more details.

For me, changing the Start In location (of git-gui at least) did not affect where it looked for .gitconfig. My setup at work mounts U: for our home, but we do not have permission to write in U: directly, only subdirectories which were created for us inside, so this was a deal-breaker for me.
I solved the problem by making a batch script which would override the HOMEDRIVE and HOMEPATH env variables just for that application. Then changed my Start menu shortcut to point to that batch script instead.

First check HOME setting, then change HOME and HOMEDRIVE to a existing dir.
c:\git>set HOME
HOME=U:\
HOMEDRIVE=U:
HOMEPATH=\
then change HOME and HOMEDRIVE by
set HOME=c:\tmp
set HOMEDRIVE=C:

Change to folder %PROGRAMFILES%\Git\etc
Edit file profile
Add to first line HOME="c:\location_were_you_want_gitconfig"
Done
Note: The file permissions are usually restricted, so change them accordingly or you won't be able to save your changes.

If you are on windows and having problem either changing environment variables or mklink because of insufficient privileges, an easy solution to your problem is to start git batch in another location.
Just right click on Git Bash.exe, click properties and change the "Start in" property to c:\my_configuration_files\.

I wanted to do the same thing. The best I could find was #MicTech's solution. However, as pointed out by #MotoWilliams this does not survive any updates made by Git to the .gitconfig file which replaces the link with a new file containing only the new settings.
I solved this by writing the following PowerShell script and running it in my profile startup script. Each time it is run it copies any settings that have been added to the user's .gitconfig to the global one and then replaces all the text in the .gitconfig file with and [include] header that imports the global file.
I keep the global .gitconfig file in a repo along with a lot of other global scripts and tools. All I have to do is remember to check in any changes that the script appends to my global file.
This seems to work pretty transparently for me. Hope it helps!
Sept 9th: Updated to detect when new entries added to the config file are duplicates and ignore them. This is useful for tools like SourceTree which will write new updates if they cannot find existing ones and do not follow includes.
function git-config-update
{
$localPath = "$env:USERPROFILE\.gitconfig".replace('\', "\\")
$globalPath = "C:\src\github\Global\Git\gitconfig".replace('\', "\\")
$redirectAutoText = "# Generated file. Do not edit!`n[include]`n path = $globalPath`n`n"
$localText = get-content $localPath
$diffs = (compare-object -ref $redirectAutoText.split("`n") -diff ($localText) |
measure-object).count
if ($diffs -eq 0)
{
write-output ".gitconfig unchanged."
return
}
$skipLines = 0
$diffs = (compare-object -ref ($redirectAutoText.split("`n") |
select -f 3) -diff ($localText | select -f 3) | measure-object).count
if ($diffs -eq 0)
{
$skipLines = 4
write-warning "New settings appended to $localPath...`n "
}
else
{
write-warning "New settings found in $localPath...`n "
}
$localLines = (get-content $localPath | select -Skip $skipLines) -join "`n"
$newSettings = $localLines.Split(#("["), [StringSplitOptions]::RemoveEmptyEntries) |
where { ![String]::IsNullOrWhiteSpace($_) } | %{ "[$_".TrimEnd() }
$globalLines = (get-content $globalPath) -join "`n"
$globalSettings = $globalLines.Split(#("["), [StringSplitOptions]::RemoveEmptyEntries)|
where { ![String]::IsNullOrWhiteSpace($_) } | %{ "[$_".TrimEnd() }
$appendSettings = ($newSettings | %{ $_.Trim() } |
where { !($globalSettings -contains $_.Trim()) })
if ([string]::IsNullOrWhitespace($appendSettings))
{
write-output "No new settings found."
}
else
{
echo $appendSettings
add-content $globalPath ("`n# Additional settings added from $env:COMPUTERNAME on " + (Get-Date -displayhint date) + "`n" + $appendSettings)
}
set-content $localPath $redirectAutoText -force
}

As someone who has been interested in this for a VERY LONG TIME. See from the manual:
$XDG_CONFIG_HOME/git/config - Second user-specific configuration file. If $XDG_CONFIG_HOME is not set or empty, $HOME/.config/git/config will be used. Any single-valued variable set in this file will be overwritten by whatever is in ~/.gitconfig. It is a good idea not to create this file if you sometimes use older versions of Git, as support for this file was added fairly recently.
Which was only recently added. This dump is from 2.15.0.
Works for me.

For me it worked very simple:
Copy ".gitconfig" from old directory: to %USERPROFILE% (standard in "c:\users\username")
Right click on start-icons of GITGUI and GITBASH and change "run in": "%HOMEDRIVE%%HOMEPATH%" to "%USERPROFILE%". Of cource you can use any other directory instead of "%USERPROFILE%".
screen shot before
screen shot after

Solution without having to change Windows HOME variable
OS: Windows 10
git version: 2.27.0.windows.1
I use portable version of Git, so all my config files are on my pen-drive(E:). This is what worked for me:
Download portable Git from https://git-scm.com/. Run the file and install it in the required location. I installed it in E:\git.
Run git-bash.exe from E:\git.
I wanted to put .gitconfig and other bash files in E, so I created a folder called home where I want them all in.
mkdir home
Go to etc folder and open the file called profile (In my case, it's E:\git\etc\profile)
Add absolute path to the home directory we created (or to the directory where you want to have your .gitconfig file located) at the end of the profile file.
HOME="E:\git\home"
Now it no longer searches in the C:\Users<username> directory for .gitconfig but only looks in your set path above.
$ git config --global --list
fatal: unable to read config file 'E:/git/home/.gitconfig': No such file or directory
It gave an error because there isn't a .gitconfig file there yet. This is just to demonstrate that we have successfully changed the location of the .gitconfig file without changing the HOME directory in Windows.

1- open D:\PortableApps\Git-2.31.1PortableByAmir\etc\profile bye notepad
2- add this to profile file:
HOME="/PortableHome"
3- create PortableHome folder in D:\PortableApps\Git-2.31.1PortableByAmir\
4- copy
C:\Users\Amir\.gitconfig
C:\Users\Amir\.git-credentials
to
D:\PortableApps\Git-2.31.1PortableByAmir\PortableHome
Note: D:\PortableApps\Git-2.31.1PortableByAmir\bin\bash.exe is not a portable git
only open D:\PortableApps\Git-2.31.1PortableByAmir\git-bash.exe

Related

How can I change powershell's $PROFILE to point to the local Documents folder instead of the one on onedrive

I just installed windows 11 on my new PC, prior to this I was using Windows 10. I was setting up my terminal when I realized that the $profile environment variable points to a onedrive document folder rather than a local folder like how it does by default on Windows 10
PS C:\Users\eclipse> echo $PROFILE
C:\Users\eclipse\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
While I could technically just create the file in the onedrive folder I really do not want to store any of my files on the cloud and Id much rather prefer to have it at C:\Users\eclipse\Documents\PowerShell\Microsoft.PowerShell_profile.ps1. This is the default value stipulated by microsoft as well for current user current profile. How can I permanently change $profile to achieve this?
As far as I know, you can't change the default environment variable $profile. Your default probably comes from having your default document folder in the OneDrive. Either disable this option in the OneDrive settings on your computer or link your new folder in the current profile ps1.
C:\Users\eclipse\OneDrive\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
$profile = C:\Users\eclipse\Documents\PowerShell\
.$profile
PowerShell refers to the Personal value of your user folders. If you're a OneDrive user and have enabled OneDrive to backup your Documents Files, it is set to C:\Users\<USERNAME>\OneDrive\Documents.
You can change/check the option by going to OneDrive Settings > Sync and backup > Manage backup
Sharing the same profile across various devices can lead to issues, e.g. when you have a certain packages installed on one machine, but not on the other. To work around this problem, there are two main options:
1. To have the shared profile refer to a local copy on your machine (preferred)
2. To edit the registry so that your documents folder points to a local directory (not preferred)
Create Local Folder and Copy Profile
To find the location of your current profile open PowerShell and run echo $profile
Create a new local directory, e.g. C:\Users\<USERNAME>\Documents\PowerShell\
Copy the PowerShell profile from the C:\Users\<USERNAME>\OneDrive\Documents\PowerShell\ directory to your new, local directory . Do not move the file! Make a copy!
Option A: Add a Link to a Local Profile
Go to the C:\Users\<USERNAME>\OneDrive\Documents\PowerShell\ directory and open the Microsoft.PowerShell_profile.ps1 file in a editor. Make sure you're editing the shared profile and not your local copy!
Clear the file and add the following line to let the shared profile refer to the copy in your local directory/copy,
&"$($UserProfile)Documents\PowerShell\Microsoft.PowerShell_profile.ps1"
Option B: Edit Registry to Change Location of User Shell Folder
Editing the registry to change the location of the User Shell folder can have knock-on effects. So it's better not to do it this way!
To change the registry, run
Set-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name "Personal" -Value "C:/Users/<USERNAME>/Documents/PowerShell/"
To test the value was set correctly, run
Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name "Personal"

How to change HOME directory and start directory on MSYS2?

I have installed MinGW-w64 and MSYS2. But how do I change the HOME directory in MSYS2? So that when I type cd $home or cd ~ it goes to another directory that I defined.
And how do I write a code so that the starting directory is always where the .bat file is placed on?
In cmd I used this code:
%~d1
cd "%~p1"
call cmd
so when I open cmd on my desktop, it starts from the directory on desktop.
How can I do a similar thing with msys2?
If you would like to use your windows home folder as the home folder for MSYS2, you can edit /etc/nsswitch.conf and write:
db_home: windows
Msys2 will use windows %HOME% as it's $HOME dir. If you set %HOME% in environment variables (to the windows directory you need Msys2 to use) it will work.
I prefer to just update /etc/fstab
# fstab.
# cat /etc/fstab
# For a description of the file format, see the Users Guide
# https://cygwin.com/cygwin-ug-net/using.html#mount-table
# DO NOT REMOVE NEXT LINE. It remove cygdrive prefix from path
none / cygdrive binary,posix=0,noacl,user 0 0
##################################################################
# Canonicalize the two home directories by mounting the windows #
# user home with the same path mapping as unix. #
##################################################################
none /c/Users/Edward /home/Edward binary,posix=0,noacl,user 0 0
In one of your shell startup scripts (e.g. ~/.bash_profile where ~ is the default/original home directory) you can change the $HOME environment variable:
export HOME=/something/else
If you want your shell to open in that directory you might need to run cd (with no arguments) after setting $HOME; I have not tested it.
Besides the above anwsers, there is another way using the Windows command mklink to make a directory symbol link, similar to ln of Linux.
First make a directory of e:\msys\home, then run cmd as Administrator, then run:
cd c:\msys64
mklink /j home e:\msys\home
no other change required.
Occasionally after specific base updates, the link got invalid, need to be made once again, after the newly generated 'home' directory cleared or renamed.
Create or modify an MSYS2 /etc/passwd file. Two ways of doing this are shown below.
The following command can be run from an MSYS2 shell, and works safely whether or not the file exists and whether or not it already contains the current user:
$ grep "^${USERNAME}:" /etc/passwd >/dev/null 2>&1 || mkpasswd | grep "^${USERNAME}:" >>/etc/passwd
Next, edit /etc/passwd, and change the relevant user's home directory field (the 6th colon-delimited field).
$ vim /etc/passwd
BONUS: It is also possible to change the MSYS2 username by editing the first field.
As desired, move current home directory content to the new home directory.
Log off, then log back in.
The /etc/passwd edits can be done without manual editing, but this makes for a more complex command-line to paste into the MSYS2 shell, and, it might not work if the /etc/passwd file already exists and has the username in it already:
__DIR="/path/to/home"
mkpasswd | grep "^${USERNAME}:" | \
awk -v DIR="${__DIR}" -v RS=":" -v ORS="/n" \
'NR == 6 { printf(DIR ":"); next } { printf("%s", $0) } NR < 7 { printf(":") }' - >>/etc/passwd
I add HOME='E:/Users/your_directory' in /etc/profile. It looks as follows:
...
# Setup some default paths. Note that this order will allow user installed
# software to override 'system' software.
# Modifying these default path settings can be done in different ways.
# To learn more about startup files, refer to your shell's man page.
MSYS2_PATH="/usr/local/bin:/usr/bin:/bin"
MANPATH='/usr/local/man:/usr/share/man:/usr/man:/share/man'
INFOPATH='/usr/local/info:/usr/share/info:/usr/info:/share/info'
HOME='e:/Users/HP'
case "${MSYS2_PATH_TYPE:-minimal}" in
...
but the shell shows the path fully, not just ~.
I've created a batch file which sets the HOME variable:
set HOME=C:\Users\%USERNAME%
C:\LocalApp\PortableGit\git-bash.exe
This allows me to put my .bash_profile in this HOME (rather than on the default network location which performs very slowly).

Set global working directory alias in Git bash (Windows)

I've been trying for literally hours to set a global alias that I can use when I open Git bash on my Windows machine to cd to a specific location.
I want to be able to simply type the alias to get to the location. I've tried every which way. The attempt that got me closest was based on this: https://superuser.com/questions/602872/how-do-i-modify-my-git-bash-profile-in-windows
...but it seems that to get it to work upon relaunching of bash, I have to use source .bashrc, which I don't want to do. Help appreciated.
I just jury rigged a solution with a simple shell script that acts like a global alias. If someone has a better solution, please do tell.
Opened text editor and wrote the following two lines:
#!/bin/bash
cd blah/blep/directory_of_choice
Saved it as a text file with a descriptive name (like dirjump) somewhere and copied it.
In file explorer, navigated to the bin folder in the MinGW64 installation, e.g. "C:\Program Files\Git\mingw64\bin"
Pasted the file into this bin folder.
While viewing the contents of the bin folder referenced above in Windows file explorer, from the menu bar selected "view > options", which opened the "folder options" dialog. Selected the "view" tab here and unchecked "Hide extensions for known file types" and clicked ok.
Deleted the ".txt" extension from the file copied into the bin folder.
To call this shell script that has the same result as a global alias, typed the following in Git bash:
. dirjump (the space between the dot and the dirjump MUST be included)

how to change gitconfig location?

I am running this command under windows 7:
git status
Now I am getting this error:
fatal: unable to access 'H:\/.config/git/config
I am disconnected from the network at the moment. Can I still fix this by changing the config location or creating a new config?
Can I still fix this by changing the config location or creating a new config?
You can simply change your environment variable HOME, in order to reference an existing local folder
set HOME=C:\local\path
In that folder, a .gitconfig can be defined in order to have a global git config file.
The msysgit/msysgit/git-cmd.bat defines it by default to:
#if not exist "%HOME%" #set HOME=%USERPROFILE%
Git will respect the HOME environment variable to determine the location of the global .gitconfig.
If asking your domain admin to reset your HOMEDRIVE and HOMEPATH variable back to your local user profile is not an option, you can simply change the HOME variable instead (which is usually unset, so there won’t be a conflict) at the top of your shell to make Git use that location.
For example, if you’re using Git Bash, you can simply add the following line to the bottom of your shell profile, located at C:\Program Files (x86)\Git\etc\profile:
export HOME="$USERPROFILE"
(I think $USERPROFILE is still left to the default even if the domain settings change your home drive. Of course, you can always specify a fixed path if that doesn’t work)
If you are using other shells, you can do similar things, for example in PowerShell:
$env:HOME = $env:USERPROFILE # or = 'C:\Users\poke\'
Of course, since the variable is unset by default, you could also set it at Windows level in your system configuration. That way, every program would use it automatically.
Afterwards, all Git commands will automatically look at $HOME\.gitconfig.
You need to specify the config file location using git config and the -f option.
git config -f your_config_file

How to default to other directory instead of home directory

I am developing on a windows machine. The only place I need for linux command line is Git Bash. The problem is: When I open it, I am in the home directory. I have to change the directory to my workspace, like:
cd ../../../d/work_space_for_my_company/project/code_source
Can I wrap this in a .sh file so I don't have to hand-type it anymore? This should be simple but I have zero knowledge about Linux command line. I am really appreciated If you can walk me
through how to create that .sh file.
Here's a more Windows-ish solution:
Right click on the Windows shortcut that you use to launch git bash, and click Properties. Change the value of "Start In" to your desired workspace path.
Edit: Also check that the Target value does not include the --cd-to-home option as noted in the comments below.
Just write that line to a file "cd.sh", then do this from your shell prompt:
. ./cd.sh
Or you can create an alias or function in your $HOME/.bashrc file:
foo() { cd /d/work_space_for_my_company/project/code_source ; }
If the directory name includes spaces or other shell metacharacters, you'll need quotation marks; it won't hurt to add them even if they're not necessary:
foo() { cd "/d/Work Space/project/code_source" ; }
(Note that I've omitted the ../../..; you don't need it.)
EDIT: If you add a line
foo
to your .bashrc after the function definition, your shell will start in that directory. Or you can just use the cd command directly in your .bashrc if you aren't going to need to use the function later.
(The name foo is just an example; you should pick a more meaningful name.)
Add the line to the .bashrc file in the home directory (create the file if it doesn't exist):
cd ~
touch .bashrc
echo "cd ~/Desktop/repos/" >> .bashrc
I use ConEmu (strongly recommended on Windows) where I have a task for starting Git Bash like
Note the button "Startup dir..." in the bottom. It adds a -new_console:d:<path> to the startup command of the Git Bash. Make it point to wherever you like
This may help you.
Right click on git bash -> properties
In Shorcut tab -> Start in field -> enter your user defined path
Make sure the Target field does not include --go-to-home or it will continue to start in the directory specified in your HOME variable
Thats it.
I also just changed the "Start in" setting of the shortcut icon to: %HOMEDRIVE%/xampp/htdocs/
(Please read warning below)
Really simple way to do this in Windows (works with git bash, possibly others) is to create an environmental variable called HOME that points to your desired home directory.
Right click on my computer, and choose properties
Choose advanced system settings (location varies by Windows version)
Within system properties, choose the advanced tab
On the advanced tab, choose Environmental Variables (bottom button)
Under "system variable" check to see if you already have a variable called HOME. If so, edit that variable by highlighting the variable name and clicking edit. Make the new variable name the desired path.
If HOME does not already exist, click "new" under system variables and create a new variable called HOME whose value is desired path.
NOTE: This may change the way other things work. For example, for me it changes where my .ssh config files live. In my case, I wanted my home to be U:\, because that's my main place that I put project work and application settings (i.e. it really is my "home" directory).
EDIT June 23, 2017: This answer continues to get occasional upvotes, and I want to warn people that although this may "work", I agree with #AnthonyRaymond that it's not recommended. This is more of a temporary fix or a fix if you don't care if other things break. Changing your home won't cause active damage (like deleting your hard drive) but it's likely to cause insidious annoyances later. When you do start to have annoying problems down the road, you probably won't remember this change... so you're likely to be scratching your head later on!
This will do it assuming you want this to happen each time you open the command line:
echo cd ../../../d/work_space_for_my_company/project/code_source >> ~/.bashrc
Now when you open the shell it will move up three directories from home and change to code_source.
This code simply appends the line "cd ../../../d/work_space_for_my_company/project/code_source" to a file named ".bashrc". The ">>" creates a file if it does not exist and then appends. The .bashrc file is useful for running commands at start-up/log-in time (i.e. loading modules etc.)
Right-click the Git Bash application link go to Properties and modify the Start in location to be the location you want it to start from.
From a Pinned Start Menu Item in Windows 10
Open the file location of the pinned shortcut
Open the shortcut properties
Remove --cd-to-home arg
Update Start in path
Re-pin to start menu via recently added
Thanks to all the other answers for how to do this! Wanted to provide Win 10 instructions...
For windows: Follow these steps-
Go to windows home> Right click on "Git Bash" application.
Properties> Shortcut
Change these two settings:
(a) Delete --cd-to-home from target
(b) Type folder path you want to start with git in "Start in".
This worked for me:)
If you want to have projects choice list when u open GIT bash:
edit ppath in code header to your git projects path, put this code into .bashrc file and copy it into your $HOME dir (in Win Vista / 7 it is usually c:\Users\$YOU)
#!/bin/bash
ppath="/d/-projects/-github"
cd $ppath
unset PROJECTS
PROJECTS+=(".")
i=0
echo
echo -e "projects:\n-------------"
for f in *
do
if [ -d "$f" ]
then
PROJECTS+=("$f")
echo -e $((++i)) "- \e[1m$f\e[0m"
fi
done
if [ ${#PROJECTS[#]} -gt 1 ]
then
echo -ne "\nchoose project: "
read proj
case "$proj" in
[0-`expr ${#PROJECTS[#]} - 1`]) cd "${PROJECTS[proj]}" ;;
*) echo " wrong choice" ;;
esac
else
echo "there is no projects"
fi
unset PROJECTS
you may want set this file as executable inside GIT bash chmod +x .bashrc (but its probably redundant, since this file is stored on ntfs filesystem)
My Git Bash shortcut on Windows complained when I put the cd to my work directory into ~/.bashrc
WARNING: Found ~/.bashrc but no ~/.bash_profile, ~/.bash_login or ~/.profile.
This looks like an incorrect setup.
A ~/.bash_profile that loads ~/.bashrc will be created for you.
So git created this .bash_profile:
$ cat ~/.bash_profile
# generated by Git for Windows
test -f ~/.profile && . ~/.profile
test -f ~/.bashrc && . ~/.bashrc
Which does the job.
Alternatively, you can just remove the .bashrc again and put the cd command into .bash_profile:
$ rm ~/.bashrc
$ echo "cd Source/Repos" >~/.bash_profile
$ cat ~/.bash_profile
cd Source/Repos
Once this is done you can close the Window and re-open it using your desktop shortcut and the prompt will tell you that your location is now where you wanted it - looks like this is my case:
Administrator#raptor1 MINGW64 ~/Source/Repos
$
If you type this command:
echo cd d:/some/path >> ~/.bashrc
Appends the line cd d:/some/path to .bashrc. The >> creates a file if it doesn’t exist and then appends.
it must be cd d:/work_space_for_....
without the : it doesn't work for me
Another solution for Windows users will be to copy the Git Bash.lnk file to the directory you need to start from and launch it from there.

Resources