What is the environment variable XDG_VTNR?

What is $XDG_VTNR? Where and when is it being set?

It's set by the pam_systemd PAM module, and is only set on machines which are using systemd, which means that you should not rely on it in your scripts, unless you want to make them depend on systemd.

On systems which are using systemd, $XDG_VTNR will be set both in graphical (by lightdm, gdm, etc) and in text-mode sessions (by /bin/login).

Where can I find the official documentation about this variable?

In the pam_systemd(8) manpage.

tty is a built-in command while $XDG_VTNR is provided by Xorg, why people choose to use $XDG_VTNR instead of built-in tty?

1) tty is a standalone program, not a built-in, and $XDG_VTNR is not provided by Xorg.

2) Because they're completely different things. As clearly stated in its manpage, tty(1) will tell you the name of the terminal connected to its standard input, not the name of the virtual terminal your GUI session or such may be running on[1]. Consider this:

$ script -q /dev/null
$ tty
/dev/pts/5
$ script -q /dev/null
$ tty
/dev/pts/6
$ tty </dev/zero
not a tty

[1] for which XDG_VTNR isn't a reliable indicator either.

Tags:

Linux

X11

Tty

Xorg