1

I need a git alias to stash then reset.

Which one should I use in my .bashrc:

git config --global alias.sr '!git stash && git reset --hard HEAD'

or,

git config --global alias.sr 'git stash && git reset --hard HEAD'

I am asking this because How can I stage and commit all files, including newly added files, using a single command? used !git and I am not sure what that actually means amd it confused me to use one or the other.

Ahmad Ismail
  • 11,636
  • 6
  • 52
  • 87
  • @L3viathan I think this qualifies for an accepted answer. So, can you please put it in the answer section. – Ahmad Ismail Oct 15 '20 at 17:37
  • This question is really about the `!` in the alias. But I will add this comment: the alias shown is pointless. That's because the last step of `git stash` is to run `git reset --hard HEAD`. Running it a second time does not produce anything useful. – torek Oct 16 '20 at 05:06

2 Answers2

1

From the git-config manpage:

If the alias expansion is prefixed with an exclamation point, it
will be treated as a shell command. For example, defining alias.new
= !gitk --all --not ORIG_HEAD, the invocation git new is equivalent
to running the shell command gitk --all --not ORIG_HEAD. Note that
shell commands will be executed from the top-level directory of a
repository, which may not necessarily be the current directory.
GIT_PREFIX is set as returned by running git rev-parse
--show-prefix from the original current directory. See git-rev-
parse(1).

So you'll need to use the form with a !. If no ! is present, git will interpret the value as a git-subcommand, e.g. git config alias.foo 'bar' will make git foo equivalent to git bar. Since you use a shell feature (the &&), you need to route it through the shell with !.

L3viathan
  • 26,748
  • 2
  • 58
  • 81
0

The accepted answer explains the shell escape, but it misses one important point: You do not need to put either of these commands in your .bashrc! The command git config stores the alias persistently in your git configuration. You just need to execute it once, and git sr will be understood -- also across reboots.

alexis
  • 48,685
  • 16
  • 101
  • 161
  • I actually do not put anything in my `.gitconfig` because I use bare repo to track my dotfiles and I can not track the `.gitconfig` with the bare repo. It messes things us when I try to restore. – Ahmad Ismail Oct 15 '20 at 17:57
  • I'm not sure I understand what you mean about the bare repo, but how do you _keep_ `git config --global` from saving the setting in your `.gitconfig`? – alexis Oct 15 '20 at 19:58
  • Now I understand what you mean. I do not need to put `git config --global alias.sr '!git stash && git reset --hard HEAD'` on my `.bashrc`. I just need to run it once in my terminal. Is it what you meant? – Ahmad Ismail Oct 15 '20 at 21:38
  • 1
    yes, exactly @blueray. This command writes the alias into your .gitconfig . – alexis Oct 16 '20 at 09:09