gpt4 book ai didi

bash - 在 Centos 服务器上的 shell 脚本中自动执行 git push 和 commit

转载 作者:行者123 更新时间:2023-12-04 19:41:20 27 4
gpt4 key购买 nike

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

到目前为止,这是我的实现:

#!/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

最佳答案

您可以使用 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 的输出相同
  • 检查命令是否存在的其他方法是通过 commandhashHowto check if a program exists in my PATH
  • 关于bash - 在 Centos 服务器上的 shell 脚本中自动执行 git push 和 commit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60735212/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com