简体   繁体   中英

Make git commit using sudo

How can one make a git commit of a folder where they don't have write access? My initial attempt was:

normaluser@host:/etc $ sudo git init
normaluser@host:/etc $ sudo git commit -m'init'

Unfortunately, this will not work. The regular user has a .gitconfig with the required name and email and I need to have git use those credentials in the commit. The root user does not have such git credentials, and therefore cannot make a commit.

git has -c option that let's you override values set in .gitconfig (or provide any new key-value pairs):

   -c <name>=<value>
       Pass a configuration parameter to the command. The value given will override
       values from configuration files. The <name> is expected in the same format as
       listed by git config (subkeys separated by dots).

So you could for example execute:

git -c user.name=user1032531 init

You could also link your user's .gitconfig as root's gitconfig or make the grant the current user access to all the files that need to be in the repo (consider using the last option).

您在此处有3个选项,您可以自己授予该文件夹的权限(即,使其可以被任何人使用),可以更改要提交到具有烫发的位置的目录,或者可以编辑git的配置文件sudo使用sudo编辑文件。

To automatically pull in my non-root user's config files, I use the bash alias:

alias gsudo='sudo git -c "include.path='"${XDG_CONFIG_DIR:-$HOME/.config}/git/config\" -c \"include.path=$HOME/.gitconfig\""

Then I use gsudo instead of git to both:

  • Run as root
  • Have access to all non-root user git configuration

Check that the config is indeed being imported:

gsudo config --list --show-origin --includes | less

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM