A while ago I checked out a previous commit, then checked out my most recent commit again. I didn't realize this at the time, but that left me in a detached head state. I've done multiple commits since then, and am still in the detached head state. I know I can get out of this state by doing git checkout <branch name>, but if I do this will I lose anything?

2

There are 2 best solutions below

2
On

I can get out of this state by doing git checkout <branch name>, but if I do this will I lose anything?

Yes, you will lose all the commits you've made in detached head mode, because no branch name will be pointing to them. (You won't totally lose them immediately, but they will be slated for destruction, and accessing them will become more difficult.)

So simply create a branch first, to retain them and give you a way to refer to them.

git switch -c temp

Now it's safe to checkout branchname.

Actually in your case, though, since your HEAD is in fact where you wish your branch was, you can just move your branch name to where you are now instead. No need for temp at all.

git switch -C branchname 
0
On

I didn't realize this at the time, but that left me in a detached head state

That is why I mention the more recent (Git 2.23, Q3 2019) git switch command.

You cannot use git switch <commit> and not realize you end up in a detached HEAD state, because such a command would actually fail, with the error message:

fatal: a branch is expected, got <commitID>
If you want to detach HEAD at the commit, try again with the `--detach` option

See more at "Why did my Git repo enter a detached HEAD state?".
The hint to use the --detach option comes from Git 2.36 (Q2 2022).