bash - 如何在shell脚本中进入文件夹并进行操作

标签 bash git shell ubuntu sh

我在服务器路径有一个目录 - /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/

相关文章:

git - 从 protected github 仓库中获取单个 LFS 文件

c - 在 tcsh shell 下,如何将脚本的输出发送到 shell 和 gdb 上的程序?

python - 运行 setup.py 时更改包名称

python - 如何在终端中打印 df 而不丢失格式?

在 bash 脚本中使用时拒绝访问 mysqldump

bash - 终端将命令应用于所有子目录

linux - 读取传递给命令的 cat 文件无法正常工作

bash - 如何在不执行的情况下编辑当前的 shell 命令?

linux - 将变量传递给子 shell 时出现问题

linux - Git- 如何在 Linux 上正确终止 ssh-agent