Как правильно устанавливать "рабочую" директорию в скрипте?

Рейтинг: 2Ответов: 1Опубликовано: 18.07.2025

Я составляю скрипт для автоматизации работы с GitLab репозиторием, клонированным локально.

Если предварительно я не перейду в директорию с клонированным репозиторием, я получаю ошибку

fatal: Not a git repository (or any parent up to mount point <path>)

Единственный знакомый мне вариант решения проблемы - команда

cd <path>

, предваряющая все следующие команды git.

Корректен ли этот подход, или существует иной способ указания "рабочей" директории для скрипта?

Ответы

▲ 4Принят

-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>. If <path> is present but empty, e.g.
       -C "", then the current working directory is left unchanged.

       This option affects options that expect path name like --git-dir
       and --work-tree in that their interpretations of the path names
       would be made relative to the working directory caused by the -C
       option. For example the following invocations are equivalent:

           git --git-dir=a.git --work-tree=b -C c status
           git --git-dir=c/a.git --work-tree=c/b status

Сравните сами:

$ ls
repo

$ git status -sb
fatal: not a git repository (or any of the parent directories): .git

$ git -C repo status -sb
## branch...origin/branch
 M changed.txt

$ cd repo

$ git status -sb
## branch...origin/branch
 M changed.txt