Getting a tool version from asdf

$ asdf current nodejs 2>&1 | sed -e "s/ \{2,\}/ /g" | cut -d" " -f2
20.17.0
Example: Print a version of Node.js managed by asdf.

Context

The following command prints a tool version managed by asdf:

$ asdf current golang
golang          1.23.3          /home/soulim/data/sources/github.com/soulim/q/.tool-versions
Print a version of Go managed by asdf.

Unfortunately there’s no way to get only the version. However that could be achieved with additional output manipulation.

Using sed and cut commands a version of given tool could be extracted using the following pipeline:

asdf current golang | sed -e "s/ \{2,\}/ /g" | cut -d" " -f2
Print only a version of Go managed by asdf.

Explanation:

  1. Print current tool version with asdf current golang.
  2. In the output from asdf replace with one space character any sub-strings consisting of multiple space characters with sed -e "s/ \{2,\}/ /g".
  3. Split resulted output on columns separated by one space character and return the second column with cut -d" " -f2.

In this form the one-liner doesn’t work well when given tool isn’t installed yet. In that case asdf doesn’t print anything to the output stream, but instead sends an error message to the error stream. Like in the following example with Node.js:

$ asdf current nodejs | sed -e "s/ \{2,\}/ /g" | cut -d" " -f2
nodejs          20.17.0         Not installed. Run "asdf install nodejs 20.17.0"
An attempt to print a version of Node.js that isn't installed yet.

To fix the issue error stream needs to be redirected to the output stream. The final version of the one-liner looks like this:

asdf current nodejs 2>&1 | sed -e "s/ \{2,\}/ /g" | cut -d" " -f2
A one-liner to print a tool version managed by asdf.

UPDATE: There’s a way to replace sed and cut with awk to simplify the solution.


TIL rating:
good to know

Read next