Git stash单独存储未跟踪的文件

Git stash单独存储未跟踪的文件

在本文中,我们将介绍如何使用Git stash单独存储未跟踪的文件。Git stash是一个非常有用的命令,它可以暂存当前工作目录的修改,以便切换到其他分支或进行其他操作。

当我们在开发过程中创建了一些新文件,但还没有将它们添加到Git仓库中时,这些文件被称为未跟踪的文件。有时候,我们可能需要将这些未跟踪的文件暂存起来,以便在切换分支或进行其他操作后再重新添加它们。

阅读更多:Git 教程

Git stash命令

Git stash命令用于暂存当前工作目录的修改。它将暂存的修改存储在一个临时区域中,并使工作目录回到干净的状态。

要使用Git stash命令单独存储未跟踪的文件,我们需要执行以下步骤:

  1. 首先,确保当前工作目录下有未跟踪的文件。可以使用git status命令来查看工作目录的状态。

  2. 执行git stash push -- <文件路径>命令,将指定的未跟踪文件暂存起来。例如,要存储名为example.txt的未跟踪文件,可以运行git stash push -- example.txt命令。

    $ git status
    On branch main
    Untracked files:
     (use "git add <file>..." to include in what will be committed)
           example.txt
    nothing added to commit but untracked files present (use "git add" to track)
    
    $ git stash push -- example.txt
    Saved working directory and index state WIP on main: b35f0e3 Commit message
    
    $ git status
    On branch main
    nothing to commit, working tree clean
    Bash

    执行该命令后,Git会将指定的未跟踪文件存储在一个临时区域中,并将工作目录回到干净的状态。

  3. 在完成其他操作后,如果需要将已存储的未跟踪文件重新添加到工作目录中,可以执行git stash apply命令。这将将存储的修改应用到当前工作目录中。

    $ git stash apply
    On branch main
    Changes to be committed:
     (use "git restore --staged <file>..." to unstage)
           modified:   example.txt
    Bash

    执行git stash apply命令后,Git将存储的未跟踪文件重新应用到当前工作目录中。

示例说明

假设我们正在开发一个Web应用程序,并且创建了一个新的HTML文件index.html。由于这是一个新文件,我们还没有将其添加到Git仓库中。现在,我们需要在切换分支之前将该文件暂存起来。

  1. 首先,使用git status命令检查工作目录的状态。
    $ git status
    On branch main
    Untracked files:
     (use "git add <file>..." to include in what will be committed)
           index.html
    nothing added to commit but untracked files present (use "git add" to track)
    
    Bash

    我们可以看到index.html文件位于未跟踪文件列表中。

  2. 执行git stash push -- index.html命令,将index.html文件暂存起来。

    $ git stash push -- index.html
    Saved working directory and index state WIP on main: b35f0e3 Commit message
    Bash

    Git将index.html文件存储在一个临时区域中,并将工作目录恢复到干净的状态。

  3. 在切换分支或进行其他操作后,如果需要将存储的index.html文件重新添加到工作目录中,可以执行git stash apply命令。

    $ git stash apply
    On branch main
    Changes to be committed:
     (use "git restore --staged <file>..." to unstage)
           modified:   index.html
    Bash

    Git将存储的index.html文件重新应用到工作目录中,并标记为修改状态。

总结

通过使用Git stash命令,我们可以方便地单独存储未跟踪的文件。这对于切换分支或进行其他操作而不希望丢失未跟踪文件的修改非常有用。使用git stash push -- <文件路径>命令可以将指定的未跟踪文件暂存起来,并使用git stash apply命令将存储的修改重新应用到工作目录中。通过这些操作,我们能够更加灵活地管理未跟踪文件的修改。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册