将系统上所有 git 个存储库的远程从 http 更改为 ssh
Change the remote of all git repositories on a system from http to ssh
最近 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 存储库的父目录上嵌套 for 循环。这将是这样的:
for DIR in *; do
for SUBDIR in DIR; do
("git remote set-url..."; cd ..;)
done
done
这将识别所有包含名为 .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 提出了一个弃用通知,即推送到我们存储库的 HTTP 方法即将过期。我决定改用 SSH 方法。在这样做时,我发现我们需要在设置密钥后更改 repos 的远程 URL。
但是更改是一个乏味的过程,并且对我本地系统上的所有存储库进行更改是一项相当漫长的工作。有什么方法可以编写一个 Bash 脚本,一个一个地遍历目录,然后将远程 URL 从 HTTP 版本更改为 SSH 版本?
这对 HTTP -> SSH 进行了必要的更改。
git remote set-url origin git@github.com:username/repo-name
我们需要更改的是repo-name
,它可以与目录名称相同。
我想到的是 运行 在包含所有 git 存储库的父目录上嵌套 for 循环。这将是这样的:
for DIR in *; do
for SUBDIR in DIR; do
("git remote set-url..."; cd ..;)
done
done
这将识别所有包含名为 .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