Aurimas
Aurimas

Reputation: 2727

How to git stash only untracked files?

I want to only stash all untracked files. I know it can be done with two commands, by first stashing tracked changes and then untracked, but can it be done with one line command?

Upvotes: 37

Views: 17026

Answers (2)

Yves Boutellier
Yves Boutellier

Reputation: 2044

For Beginners (with example)

Imagine you are on branch A, but you want to commit only changes to existing files, while the newly created file should be committed to a new branch B.

Add script (by vsminkov) to .git/config

Inside the .git folder there is a config file. Open it up and you will see something like this:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[remote "origin"]
    url = https://github.com/...
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
    remote = origin
    merge = refs/heads/main

change the config file to:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = true
[alias]
    stash-untracked = "!f() {    \
                git stash;               \
                git stash -u;            \
                git stash pop stash@{1}; \
            }; f"
[remote "origin"]
    url = https://github.com/...
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "main"]
    remote = origin
    merge = refs/heads/main

Now you will be able to use the following command while you are on branch A.

git stash-untracked

You will see that the new file disappeared, if you are using a editor like VSCode (it's now stashed)

While still on branch A stage and commit the changes to the existing files:

git add .
git commit -m "committing tracked changes to current branch"

Next step is creating a new branch B (with checkout -b you visit it immediately)

git checkout -b newBranchName

When using stash pop the stashed changes get added to your current branch.

git stash pop

The only thing left is to stage and commit the changes on the new branch B

git add .
git commit -m "created new file"

Upvotes: 5

vsminkov
vsminkov

Reputation: 11270

You can do it with alias in ~/.gitconfig:

stash-untracked = "!f() {    \
    git stash;               \
    git stash -u;            \
    git stash pop stash@{1}; \
}; f"

And then just do

git stash-untracked

Upvotes: 56

Related Questions