【问题标题】:Use bash script to store output of git commands and send it in email使用 bash 脚本存储 git 命令的输出并通过电子邮件发送
【发布时间】:2019-11-17 08:52:20
【问题描述】:

这是我的小脚本...它所做的只是遍历一些文件夹,检查修改过的文件,提交对 git 的更改,但同时存储要通过电子邮件发送的 git 消息的输出作为报告:

#!/bin/bash

enviromentName=xyz
serverName=abc
serverSize=1GB

cd /home/$enviromentName/domains/
domainsArray=(*/)
changes=0
message="Usage (max ${serverSize}): $(du -h --max-depth=0 | head -n1 | awk '{print $1;}')\n"
currentDate=$(date +%Y%m%d)

cd /home/$enviromentName/
for i in "${domainsArray[@]}"
do
        cd /home/$enviromentName/domains/$i/public_html/
        gitstatus=$(git status)
        if echo $gitstatus | grep -v -q "nothing to commit, working directory clean"; then
                message+="\n"
                message+="  Git Changes made to ${i}:\n"
                message+="'$gitstatus'\n"
                message+="$(git add .)\n"
                message+="$(git commit -m ${currentDate})\n"
                message+="\n"
                changes=1
        fi
done

if [ "$changes" -eq "1" ]; then
        #echo "Changes done"
        echo -e ${message}|mail -s "${serverName} logs" marcin@citystudio.pl
fi

脚本的输出如下所示:

Usage (max 1GB): 0.5G

Git Changes made to foldername/:
'On branch master Untracked files: (use "git add <file>..." to include in what will be committed) test.php nothing added to commit but untracked files present (use "git add" to track)'

[master d4d3916] 20190707 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 public_html/test.file

看起来 git 命令输出的所有换行符似乎都消失了。我应该如何修改脚本,使输出看起来像这样:

Usage (max 1GB): 0.5G

  Git Changes made to foldername/:
On branch master
Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    test.php

no changes added to commit (use "git add" and/or "git commit -a")
[master 86f39b9] 20190707
 1 file changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 public_html/test.php

【问题讨论】:

  • 你需要对变量引用进行双引号;这只是您不这样做时可能出错的众多事情之一。请参阅When is double-quoting necessary? 此外,您应该在每次cd 时检查错误,否则失败可能会使脚本的下一位运行在错误的位置。 shellcheck.net 擅长指出此类常见错误。
  • 最后,避免echo -e,因为它不适用于所有版本的echo(我曾经有一次操作系统版本升级破坏了我的一堆脚本,因为我使用了echo -n,它有同样的问题)。相反,使用 ANSI C 引用模式在字符串中包含文字换行符,例如message+=$'\n'

标签: linux bash git email


【解决方案1】:

出现问题是因为%{} 去除了尾随的换行符。你需要做的就是改变

echo -e ${message}|mail -s "${serverName} logs" marcin@citystudio.pl

到

echo -e "${message}"|mail -s "${serverName} logs" marcin@citystudio.pl

This 链接提供了一些很好的附加信息。

【讨论】:

  • 正确的解决方案,错误的解释。它不是“剥离”换行符,而是将所有空格(通常是空格、制表符和换行符)转换为“单词”分隔符,将生成的“单词”作为参数传递给echo,然后echo 将其参数与空格。如果任何“单词”包含任何看起来像文件名通配符的内容,它也会尝试扩展这些内容。
猜你喜欢
  • 1970-01-01
  • 2015-03-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-02
  • 1970-01-01
相关资源
最近更新 更多