如何在GIT中向文件添加chmod权限?

Hen*_*hiu 139 git

我想git提交一个.sh文件,但是当我在另一台服务器上检出同一个文件时,希望它是可执行的.

有没有办法这样做没有手动chmod u + x文件在签出文件的服务器?

Ant*_*ane 220

根据官方文档,您可以使用update-index子命令在任何跟踪的文件上设置或删除"可执行"标志.

使用

git update-index --chmod=+x path/to/file
Run Code Online (Sandbox Code Playgroud)

设置标志和

git update-index --chmod=-x path/to/file
Run Code Online (Sandbox Code Playgroud)

删除它.

在引擎盖下

虽然这看起来像常规的unix文件权限系统,但实际上并非如此.Git为其内部存储中的每个文件维护一个特殊的"模式":

  • 100644 对于常规文件
  • 100755 对于可执行的

您可以使用ls-file子命令将其可视化,并带有以下--stage选项:

$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0       .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0       my_executable_script.sh
Run Code Online (Sandbox Code Playgroud)

默认情况下,当您将文件添加到存储库时,Git将尝试遵循其文件系统属性并相应地设置正确的文件模式.您可以通过将core.fileModeoption 设置为false 来禁用此功能:

git config core.fileMode false
Run Code Online (Sandbox Code Playgroud)

故障排除

如果在某些时候没有设置Git文件模式但文件具有正确的文件系统标志,请尝试删除模式并再次设置:

git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file
Run Code Online (Sandbox Code Playgroud)

奖金

从Git 2.9开始,您可以暂存文件并在一个命令中设置标志:

git add --chmod=+x path/to/file
Run Code Online (Sandbox Code Playgroud)


tor*_*rek 21

Antwane的答案是正确的,这应该是一个评论,但评论没有足够的空间,不允许格式化.:-)我只想补充一点,在Git中,文件权限被记录只有1为两种644755(拼写(100644100755;该100部分是指"普通文件"):

diff --git a/path b/path
new file mode 100644
Run Code Online (Sandbox Code Playgroud)

前者-644-意味着该文件应该不会是可执行的,而后者意味着它应该是可执行的.如何在文件系统中转换为实际文件模式在某种程度上取决于操作系统.在类Unix系统上,这些位通过您的umask设置传递,通常是022从"组"和"其他" 002中删除写入权限,或者仅从"其他"删除写入权限.077如果您特别关注隐私并希望从"组"和"其他"中删除读取,写入和执行权限,则可能也是如此.


1早期版本的Git保存了组权限,因此某些存储库具有模式664中的树条目.Modern Git没有,但由于任何对象的任何部分都无法更改,因此旧的权限位仍然存在于旧的树对象中.

  • @ user5359531版本在提交`e44794706eeb57f2ee38ed1604821aa38b8ad9d2`之前,即早于Git版本0.99。 (2认同)

Max*_*Max 9

要将可执行标志设置为存储库中的所有文件:

git ls-files --stage |grep 100644 | cut -f2 | xargs -d '\n' git update-index --chmod=+x
Run Code Online (Sandbox Code Playgroud)

要取消所有文件的可执行标志,请执行相反的操作

git ls-files --stage | grep 100755 | cut -f2 | xargs -d '\n' git update-index --chmod=-x
Run Code Online (Sandbox Code Playgroud)

...并设置所有.sh-scripts 可执行文件,也许这是您的方式:

git ls-files --stage | grep  ".sh$" | cut -f2 | xargs -d '\n' git update-index --chmod=+x
Run Code Online (Sandbox Code Playgroud)

  • 希望没有名为“100644”或“100755”的文件;) (4认同)

Kas*_*hio 8

在 Linux 上,不要忘记

set sudo chmod +x /path/to/file
Run Code Online (Sandbox Code Playgroud)

除了在本地进行 git 更新之外,否则 git 总是会将索引恢复到本地计算机上默认设置的 644!

在 Windows Powershell 中,您可以使用

icacls .\path\to\file /grant Everyone:F
Run Code Online (Sandbox Code Playgroud)

  • 注意:令人烦恼的是,Windows 用户组是本地化的,因此“Everyone”可能不起作用。您可以使用“icacls build.sh /grant *S-1-1-0:F”代替,请参阅https://learn.microsoft.com/en-us/windows/security/identity-protection/access-control/用于查找其他组 SID 的特殊身份 (2认同)