I want to extract and verify go version in Makefile.
This works in shell:
% go version | read _ _ version _ && echo "A $version Z"
A go1.21.1 Z
But doesn't work in Makefile
check-golang-version:
go version | read _ _ version _ && echo "A $$version Z"
The result:
% make check-golang-version
go version | read _ _ version _ && echo "A $version Z"
A Z
Ultimately I wanted to have check like this:
check-golang-version:
go version | read _ _ version _ && test "$$version" = "go1.21.1" || $(error "wrong go version: $$version")
By default, make
uses /bin/sh
as the shell (see 5.3.2 Choosing the Shell).
And it's very likely that when you execute the command in a shell, the shell is zsh
. The zsh
pipeline behaviors differently from most of the other shells. See https://riptutorial.com/zsh/example/19869/pipes-and-subshells for an example.
I would recommend to use go env GOVERSION
to get the version of go and assign it to a Makefile variable:
version = $(shell go env GOVERSION)
check-golang-version:
ifneq ($(version), go1.21.1)
$(error wrong go version: $(version))
endif