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?
Another common thing you may want to do with stash is to stash the untracked files as well as the tracked ones. By default, git stash will stash only modified and staged tracked files. If you specify --include-untracked or -u , Git will include untracked files in the stash being created.
In some cases, you may want to stash a specific file in order to retrieve it later on. To stash a specific file, use the “git stash push” command and specify the file you want to stash. However, the other tracked files that may be modified in your current working directory are untouched.
Using git stash to delete files in a safer way Another method of getting a clean working directory is to use git stash to stash and delete both tracked and untracked files. You can do this using the --include-untracked command, which stashes all untracked files and then runs git clean behind the scenes for us.
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
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
.
.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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With