0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

git mv を使ってGit管理下のファイルをリネームする方法

Posted at

はじめに

Gitを使用している際に、ファイル名を変更したいケースがあります。
本記事ではGitのインデックスに登録されてるファイルの名前を変更したい時に、コマンドを操作(git add git rmgit mv )でファイル名をリネームする方法について記載します。

ゴール

git mv でインデックスに登録されたファイルの名前をリネームする

テストファイルの作成(準備)

テストあるファイルを作成しコミットまでやっておきます。

# テストファイルを作成
echo "これはサンプルテキストファイルです" > old_filename.txt

# インデックスに追加
git add old_filename.txt

# コミット
git commit -m "Add test file"

Gitでのファイル管理の基本的な流れ

Gitでファイルを管理する際、通常は以下のような流れで操作します。

  1. ワークツリー(作業ディレクトリ)でファイルの編集
  2. その変更を git add コマンドでインデックスに登録
  3. インデックスに登録された変更は git commit でローカルリポジトリに保存
  4. 最終的に git push でリモートリポジトリに反映

image.png

ファイル名の変更手順

1. git add & git rm を使った場合

ワークツリーでファイル名を変更してもインデックスには以前のファイル名が登録されたままなので、git rmでインデックスに登録されてるファイル名を削除します。
git addで新しい名前のファイルをインデックスに登録します。

# 1. ファイル名を変更
mv old_filename.txt new_filename.txt

# 2. 古いファイルをインデックスから削除(出力:rm 'old_filename.txt')
git rm old_filename.txt

# インデックスの状態を確認(削除された状態、出力:何もでない)
git ls-files

# 3. 新しいファイルをインデックスに追加
git add new_filename.txt

# インデックスの状態を確認(新しい名前で登録された状態、出力:new_filename.txt)
git ls-files

git ls-files:インデックスに登録されているファイル名の一覧を表示する

2. git mv を使った場合

git mvを使用すると上記 1. git add & git rm を使った場合 でやっていた複数のステップを1度のコマンドで実行できます。
git mv は名前変更とインデックスの登録を一度で行える便利なコマンドです。これにより操作を簡略化できます。Git管理しているファイル名の変更には個人的にこちらを使用した方が良いと思います。

# git mv 古いファイル名 新しいファイル名
git mv old_filename.txt new_filename.txt

# インデックスの状態を確認(新しい名前で登録された状態、出力:new_filename.txt)
git ls-files
0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?