【问题标题】:Change the remote of all git repositories on a system from http to ssh将系统上所有 git 存储库的远程从 http 更改为 ssh
【发布时间】:2021-05-05 21:15:40
【问题描述】:

最近 Github 提出了一个弃用通知,即推送到我们存储库的 HTTP 方法即将到期。我决定更改为 SSH 方法。在这样做时,我发现我们需要在设置密钥后更改 repos 的远程 URL。

但是更改是一个乏味的过程,并且对我本地系统上的所有存储库进行更改是一项相当漫长的工作。有什么方法可以编写一个 Bash 脚本,逐个遍历目录,然后将远程 URL 从 HTTP 版本更改为 SSH 版本?

这会从 HTTP -> SSH 进行必要的更改。

git remote set-url origin git@github.com:username/repo-name

我们需要更改的是repo-name,它可以与目录名称相同。

我想到的是在包含所有 git repos 的父目录上运行一个嵌套的 for 循环。这将是这样的:

for DIR in *; do
    for SUBDIR in DIR; do
        ("git remote set-url..."; cd ..;)
    done
done

【问题讨论】:

    标签: linux bash git ssh windows-subsystem-for-linux


    【解决方案1】:

    这将识别包含名为 .git 的文件或文件夹的所有子文件夹,将其视为一个存储库,然后运行您的命令。

    我强烈建议您在运行之前进行备份。

    #!/bin/bash
    
    USERNAME="yourusername"
    
    for DIR in $(find . -type d); do
    
        if [ -d "$DIR/.git" ] || [ -f "$DIR/.git" ]; then
    
            # Using ( and ) to create a subshell, so the working dir doesn't
            # change in the main script
    
            # subshell start
            (
                cd "$DIR"
                REMOTE=$(git config --get remote.origin.url)
                REPO=$(basename `git rev-parse --show-toplevel`)
    
                if [[ "$REMOTE" == "https://github.com/"* ]]; then
    
                    echo "HTTPS repo found ($REPO) $DIR"
                    git remote set-url origin git@github.com:$USERNAME/$REPO
    
                    # Check if the conversion worked
                    REMOTE=$(git config --get remote.origin.url)
                    if [[ "$REMOTE" == "git@github.com:"* ]]; then
                        echo "Repo \"$REPO\" converted successfully!"
                    else
                        echo "Failed to convert repo $REPO from HTTPS to SSH"
                    fi
    
                elif [[ "$REMOTE" == "git@github.com:"* ]]; then
                    echo "SSH repo - skip ($REPO) $DIR"
                else
                    echo "Not Github - skip ($REPO) $DIR"
                fi
            )
            # subshell end
    
        fi
    
    done
    

    【讨论】:

    • 这是一个很好的起点。一些建议:最好只在 Github 存储库上执行此操作。理想情况下,它会遍历所有遥控器而不是硬编码origin,并且会跳过非 Github 和非 http 遥控器。
    • 我用@JohnKugelman 的建议更改了脚本以跳过非http,并且只对github repos 执行此操作。对于遍历所有遥控器,它将如何影响git config --get remote.origin.url
    • 另外,我认为我们不需要USERNAME,这可以从$REMOTE 变量中的repo 远程URL 中推断出来。那里需要一些正则表达式的爱,我可以稍后再做,或者其他人可以继续改进它。
    • 因为它是一次性使用,所以让它变得越来越灵活肯定会带来递减的收益。
    • 这也是 Bash 4+ 中 shopt -s globstar 的一个很好的用例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    • 2017-03-07
    • 1970-01-01
    • 2013-09-24
    相关资源
    最近更新 更多