【发布时间】: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'