TLDR: Problem: kpsewhich outputs \par for unset environment variables and I do not know how to strip it.
I was inspired from the question Can I access system/environment variables from LaTeX? For instance, $HOME after finding out that kpsewhich works without --shell-escape and am trying to create a switch based on whether or not a given environment variable is set. Then I can check if e.g. DARK is set and swap text and background color.
However the problem emerged that even for unset environment variables kpsewhich apparently outputs a newline which leads to the captured output not being empty. I already tried to strip it using \tl_trim_spaces:N (as is already the case in the linked answer) but to no avail.
Is it somehow possible to either (a) instruct kpsewhich not to print a newline for unset environment variables, (b) read the return code from sys_get_shell:nnN as kpsewhich fails with a non-zero exit code if the variable is not set or (c) strip the resulting \par from the variable?
Credit goes to @Phelype Oleinik, check out his anwer for an explanation and also check out @egreg's answer for a solution without changing \endlinechar
I could now implement what I wanted using the following code:
\documentclass{article}
\usepackage{fontspec}
\usepackage{xparse}
\usepackage{xcolor}
\ExplSyntaxOn
\NewDocumentCommand{\ifenvset}{m m}
{
\sys_get_shell:nnN { kpsewhich ~ --var-value ~ #1 }
{ \int_set:Nn \tex_endlinechar:D { -1 } }
\l_tmpa_tl
\tl_if_empty:NTF { \l_tmpa_tl } {} { #2 }
}
\ExplSyntaxOff
\ifenvset{DARK}{
\pagecolor{black!90}
\color{white!90}
}
\begin{document}
\noindent
\verb|lualatex darkmode.tex|\
\verb|env DARK=1 lualatex darkmode.tex|\
\end{document}

\par(you can run it on the commandline, it is generated by tex from the the implicit end-of file as you input the result, it's probably adjustable but it would help people test answers if you provided a test document – David Carlisle Jun 10 '20 at 21:13\endlinechar=-1comment under his question so you ignore the eol – David Carlisle Jun 10 '20 at 21:15\tl_if_blank,\tl_to_strand\tl_count– Septatrix Jun 10 '20 at 21:23