我在服务器路径有一个目录 - /home/user/repos 我所有的项目文件夹都放在哪里。比如项目-a、项目-b、项目-c等。
我在代码下面放置的这个 gitpull.sh 文件位于路径 /home/user/automation/git/gitpull.sh
现在我的要求是:我想每天在特定时间自动执行所有项目的 git pull,这将在 CRON 中设置。但我面临的问题是我将放入 CRON 的文件不起作用。
我创建了一个 shell 脚本来从当前目录中提取所有 git 存储库,它工作正常。但无法理解如何从指定目录的子目录中执行 git pull,(在我的情况下是 /home/user/repos ):
我写了下面的代码:
#!/bin/bash
REPOSITORIES="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
IFS=$'\n'
for REPO in `ls "$REPOSITORIES/"`
do
if [ -d "$REPOSITORIES/$REPO" ]
then
echo "Updating $REPOSITORIES/$REPO at `date`"
if [ -d "$REPOSITORIES/$REPO/.git" ]
then
cd "$REPOSITORIES/$REPO"
git status
echo "Fetching"
git fetch
echo "Pulling"
git pull
else
echo "Skipping because it doesn't look like it has a .git folder."
fi
echo "Done at `date`"
echo
fi
done
我试着写
REPOSITORIES="$( cd "/home/user/repos/")"
和
REPOSITORIES="$( cd "/home/user/repos/*")"
但没有任何效果。
最佳答案
您可以使用 -C
git
的选项.来自 man git
:
-C path
Run as if git was started in
path
instead of the current working directory. When multiple-C
options are given, each subsequent non-absolute-C path
is interpreted relative to the preceding-C path
....
例如:
#!/bin/sh
REPOSITORIES="/home/user/repos"
for repo in "$REPOSITORIES"/*/; do
echo "Updating $repo at `date`"
if [ -d "$repo/.git" ]; then
git -C "$repo" status
echo "Fetching"
git -C "$repo" fetch
echo "Pulling"
git -C "$repo" pull
else
echo "Skipping because it doesn't look like it has a .git folder."
fi
echo "Done at `date`"
echo
done
该行:
for repo in "$REPOSITORIES"/*/; do
让您iterate over just directories ,然后如果它包含一个 git 存储库,则在该目录上运行 git 命令。
编辑 :添加目录基本路径
关于bash - 如何在shell脚本中进入文件夹并进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62199780/