最近 Github 发布了一条弃用通知,称推送到我们存储库的 HTTP 方法即将过期。我决定改用SSH方式。这样做时,我发现我们需要在设置密钥后更改存储库的远程 URL。
但是更改是一个乏味的过程,并且对本地系统上的所有存储库进行更改是一项相当漫长的工作。我们是否可以编写一个 Bash 脚本来逐一遍历目录,然后将远程 URL 从 HTTP 版本更改为 SSH 版本?
这对 HTTP -> SSH 进行了必要的更改。
git remote set-url origin [email protected]: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)
# uses quotes to allow spaces in path
REPO=$(basename "`git rev-parse --show-toplevel`")
if [[ "$REMOTE" == "https://github.com/"* ]]; then
echo "HTTPS repo found ($REPO) $DIR"
git remote set-url origin [email protected]:$USERNAME/$REPO
# Check if the conversion worked
REMOTE=$(git config --get remote.origin.url)
if [[ "$REMOTE" == "[email protected]:"* ]]; then
echo "Repo \"$REPO\" converted successfully!"
else
echo "Failed to convert repo $REPO from HTTPS to SSH"
fi
elif [[ "$REMOTE" == "[email protected]:"* ]]; then
echo "SSH repo - skip ($REPO) $DIR"
else
echo "Not Github - skip ($REPO) $DIR"
fi
)
# subshell end
fi
done
刚刚创建了一个工具来实现@paulo-amaral 提供的解决方案。 你可以找到它(在这里)[https://github.com/hondacy/developer-tools]