发布于 2026-01-06 0 阅读
0

Bash ~ 再也不用担心忘记提交 git commit 了💥

Bash ~ 再也不用担心忘记提交 git commit 了💥

你是:

  • ✅ 厌倦了提交 Git 失败
  • ✅ 厌倦了分阶段的变化
  • ✅ 同事抱怨他们缺少代码
  • ✅ 因为笔记本电脑坏了而生气,但你又没做出什么承诺?

那么这篇文章就是为你准备的!

今天我们将编写一个bash脚本,可以在一天结束时运行。
它会遍历我们的项目目录,并告诉我们每个项目的以下统计信息:

  • 这是一个 Git 仓库吗?
  • 你是不是忘了提交什么文件?
  • 我们是否有未明确说明的变化

来看看如何优化你的晨间习惯

它看起来会是这样:

使用 Bash 显示 Git 状态

Bash git commit 提示脚本

今天我们将一起分析一个bash脚本。
我会逐节讲解。最后,我会把脚本上传到 GitHub,供大家下载。

我们首先来定义变量。

将其更改DIR为您的项目文件夹。

DIR=~/www/
GITBASED=.git
Enter fullscreen mode Exit fullscreen mode

然后我们需要遍历项目文件夹中的每个子目录。

for dir in $DIR*
do
    // Loop here
done
Enter fullscreen mode Exit fullscreen mode

然后,在循环内部,我们首先需要检查我们正在检查的是否是一个目录:

if [[ -d $dir ]]; then
    // Yes I'm a directory
fi
Enter fullscreen mode Exit fullscreen mode

您可以看到我们根据-d(目录)检查目录。

如果是目录,我们就可以操作它:

我们将cd进入该目录并定义一条空消息。

cd $dir
MSG="";
Enter fullscreen mode Exit fullscreen mode

然后我们检查它是否是 Git 项目。
如果不是 Git 项目,我们就修改消息。

if [ -d "$GITBASED" ]; then
        // Git based!
else 
    // Not a valid git project
    MSG=": Not a valid git project 👀"
fi
Enter fullscreen mode Exit fullscreen mode

如果是 git 项目,我们将首先定义一个测试变量来执行git status

TEST=$(git status $dir);
Enter fullscreen mode Exit fullscreen mode

我们的变量 TEST 现在包含了返回值,接下来git status我们将使用一些if...else语句来检查它是否包含某些子字符串:

if [[ $TEST == *"nothing to commit"* ]]; then
    MSG=": No changes ✅"
// Check if git status has unstaged changes
elif [[ $TEST == *"Changes not staged for commit"* ]]; then
    MSG=": Unstaged changes 🤷‍♂️"
// Check if git status has uncommitted changes
elif [[ $TEST == *"Untracked files"* ]]; then
    MSG=": You forgot to commit some files 😡"
fi 
Enter fullscreen mode Exit fullscreen mode

最后,我们将回显以项目名称为前缀的消息,并将目录改回原来的目录。

echo ${dir##*/}$MSG
cd ..
Enter fullscreen mode Exit fullscreen mode

就是这样!

运行bash.sh脚本后,我们将获得每个项目文件夹中所有包含状态的行。

运行命令:sh bash.sh

再也没有理由忘记你的提交记录了!

下班后可以在我的 GitHub上找到这个项目

感谢阅读,让我们保持联系!

感谢您阅读我的博客。欢迎订阅我的电子邮件简讯,也可以在FacebookTwitter上关注我。

文章来源:https://dev.to/dailydevtips1/bash-never-forget-to-git-commit-again-2b3m