LoginSignup
5
2

More than 1 year has passed since last update.

git pushしたファイルをローカルに残しつつgit管理から外したい

Last updated at Posted at 2022-02-08

タイトル通り、git pushしたファイルを「git管理から外したい、でもローカルには残したい」場合の手順です。

再現手順も掲載しています。
挙動を深掘りしたい場合はご自分で検証してみてください!

これだけでOK

手短に実行コマンドのみ紹介します。

ファイル構成

ファイルは両方とも一度コミットされた状態です。
test2.txtをgit管理から除外します。

$ tree
.
├── test1.txt
└── test2.txt

.gitignoreの作成

$ echo "test2.txt" >> .gitignore

ローカルに残しつつgit管理から除外

$ git rm --cached test2.txt

コミット

$ git add .
$ git commit -m "test2 ignore"

プッシュ

$ git push

実行結果

ローカルではtest2.txtのファイル自体は残りますが、git管理から除外された状態になります。
リモートリポジトリ上では削除されます。

再現手順

上記コマンドの再現手順です。
実際に自分で操作してみると理解が深まります!

コマンドの詳細も説明しています。

GitHubで実行

リモートリポジトリgitignore_testを作成します。

リポジトリを作成する

ローカルで実行

事前準備

ファイルを作成します。

$ mkdir gitignore_test
$ cd gitignore_test
$ echo "test1" >> test1.txt
$ echo "test2" >> test2.txt

リポジトリを作成します。

$ git init

一度コミットします。

$ git add .
$ git commit -m "test1 test2 create"

デフォルトブランチの名前がmasterの場合はmainへリネームします。

$ git branch -M main

リモートリポジトリを設定します。

$ git remote add origin [git@github.com](mailto:git@github.com):*****/gitignore_test.git

プッシュします。

$ git push -u origin main

.gitignoreの作成

$ echo "test2.txt" >> .gitignore

ローカルに残しつつgit管理から除外

test2.txtをgit管理から除外します。
cachedオプションでローカルにファイルを残したままgit管理から除外することができます。

$ git rm --cached test2.txt

コマンド実行後、test2.txtはインデックスに登録されます。

$ git status
On branch main
Your branch is up to date with 'origin/main'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    deleted:    test2.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .gitignore

この時点でtest2.txtがgit管理から除外されていることが確認できます。

$ git ls-files
test1.txt

コミット

.gitignoreの作成とtest2.txtの除外コミットは同時に実行したいので、.gitignoreもインデックスに登録しコミット対象に含めます。

$ git add .

コミットします。

$ git commit -m "test2 ignore"
[main acbb8df] test2 ignore
 2 files changed, 1 insertion(+), 1 deletion(-)
 create mode 100644 .gitignore
 delete mode 100644 test2.txt

プッシュ

$ git push

git rm --cachedの注意点

git rm --cachedを実行した状態つまり「特定のファイルをローカルに残しつつgit管理から外した」状態は、コマンドを実行した環境にのみ適用されます。
そのため、複数人でリポジトリを管理している場合は注意が必要です。

  • git rm --cachedを実行した環境
    対象ファイルがgit管理から除外されるが、ファイル自体はローカルに残る。

  • それ以外の環境
    上記の環境で実行されたコミットをgit pullするだけなので、ローカルの対象ファイルが削除される。

自分一人で管理するリポジトリであれば問題ありません。

しかし、チーム開発の場合は各メンバーの環境が異なると動作確認に支障が生じます。開発途中で「特定のファイルをローカルに残しつつgit管理から外す」運用は慎重に行うべきかと思います。

参考資料

採用PR

弊社で一緒に働く仲間を募集しています。
全てのオタクを幸せにしたい方、是非ご覧ください!

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2