threads / discuss / 66472

git-rev-parse(1): not printing HEAD

Subject: git-rev-parse(1): not printing HEAD

## tl;dr

One message between Oct 6, 2026 and Oct 6, 2026.

replies: 0people: 1as markdown or json

Alejandro Colomar· Oct 6, 2026, 12:53 UTC · lore
Hi!

I'm imitating the argument-parsing of git-rebase(1) in a shell script. For the <branch> argument, if the user specifies a branch name, we should use the name; if it specifies something else, we should use that *as a detached HEAD*; and if it doesn't specify anything, we should use the active branch (if there's one), or the detached HEAD (else).

I've implemented it this way:
	if test $# -lt 1; then
		git rev-parse --abbrev-ref HEAD;
		git rev-parse HEAD;
	else
		git rev-parse --verify --symbolic "$1";
		git rev-parse --verify "$1";
	fi \
	| sed '/^HEAD$/d' \
	| sed '1!d' \
	>"$dir/head-name";

I wonder if I'm overthinking and maybe there's a simpler way. Or maybe this is the way.

The script above works by defaulting to HEAD if not specified, or using the commit ID in $1 (I've shifted, so it's just the last parameter) if specified. In the case where HEAD is explicitly specified, the user wants a detached HEAD, while if we've done it, we want to try the active branch if any.

The sed(1) part (together with the second commmand in each branch) makes sure we never keep the literal HEAD, but rather a reference or a hash.

Is this the simplest way to do it, or is there a better way to do it?

Have a lovely day! Alex

-- 
<https://www.alejandro-colomar.es>

← back to recent threads