【问题标题】:Automating git push and commit in a shell script on a Centos server在 Centos 服务器上的 shell 脚本中自动化 git push 和 commit
【发布时间】:2020-06-29 06:59:49
【问题描述】:

我正在实现一个 shell 脚本,它将备份数据库,然后将 sql 文件推送到 Github,我使用的是项目位于 /opt/server-scripts/backup.sh 的 centos 服务器。我该如何自动化呢?

这是我目前的实现:

#!/bin/bash/

var=$CURRENT_DATE=date +"%D %T"

docker exec 3856a8e52031 /usr/bin/mysqldump -u root --password=cvxxx  django_mysql_docker > backup.sql


# Git Push 

GIT=$(which git)
REPO_DIR=/opt/server-scripts/
cd ${REPO_DIR} || exit
${GIT} add --all .
${GIT} commit -m "backup:" + "'$CURRENT_DATE'"
${GIT} https://pmutua:xxxxx@github.com/pmutua/sqlbackup.git master

【问题讨论】:

  • 通过shellcheck.net验证您的脚本
  • var=$CURRENT_DATE=date +"%D %T" 更改为CURRENT_DATE=$(date +"%D %T")

标签: bash shell centos


【解决方案1】:

您可以使用type 的一种方式检查是否安装了命令/可执行文件或它是否在您的 PATH 中。

if type -P git >/dev/null; then
  echo 'git is installed.'
fi

如果你想否定结果添加!

if ! type -P git >/dev/null; then
  echo 'git is not installed.'
fi

将其添加到您的脚本中。

#!/usr/bin/env bash


docker exec 3856a8e52031 /usr/bin/mysqldump -u root --password=cvxxx  django_mysql_docker > backup.sql

if ! type -P git >/dev/null; then   ##: Check if git is not installed
  echo 'git is not installed.' >&2  ##: print an error message to stderr
  exit 1                            ##: Exit with an error
fi

# Git Push 

CURRENT_DATE=$(date +"%D %T")  ##: Assign the output of date in a variable 
REPO_DIR=/opt/server-scripts/
cd "${REPO_DIR}" || exit
git add --all .
git commit -m "backup: '$CURRENT_DATE'"
git push https://pmutua:xxxxx@github.com/pmutua/sqlbackup.git master
  • 可以直接加日期git commit -m "backup: '$(date +"%D %T")'" 这样date 将与git log 的输出相同
  • 检查命令是否存在的其他方法是通过commandhash 参见Howto check if a program exists in my PATH

【讨论】:

    猜你喜欢
    • 2012-08-12
    • 1970-01-01
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    相关资源
    最近更新 更多