如何转到 shell 脚本中的文件夹并执行操作

How to go to a folder in shell script and do the operation

我在服务器路径中有一个目录 - /home/user/repos 我所有的项目文件夹都放在那里。如项目-a、项目-b、项目-c 等。 我放在代码下方的这个 gitpull.sh 文件位于路径 /home/user/automation/git/gitpull.sh

现在我的要求是:我想在每天的特定时间自动执行所有项目的 git 拉取,我将在 CRON 中设置。但我面临的问题是我将放入 CRON 的文件无法正常工作。

我已经创建了一个 shell 脚本来从当前目录中提取所有 git 存储库,它工作正常。但是无法理解如何从指定目录的子目录中提取 git,(在我的例子中是 /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/*")"

但没有任何效果。

您能否更具体地说明什么不起作用?脚本有任何作用吗?

repos目录下有脚本吗?

REPOSITORIES="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

为您提供实际脚本所在的目录,而不是您 运行 它所在的目录。

REPOSITORIES="$( cd "/home/user/repos/")"

不会工作,因为你只是启动一个子 shell,更改目录,然后实际上没有输出任何东西。如果你只想硬编码目录名,那么这样做:

REPOSITORIES="/home/user/repos"

此外,遍历 ls 的输出是不好的做法,ls 输出不是设计为以编程方式解析的。使用

for REPO in "$REPOSITORIES"/*

您可以使用 git-C 选项。来自 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 命令。

编辑: 添加目录基本路径