The clear loop is right to skip anything that isn't closing, but sudo is on the wrong side of the pipe. stdin is the session list, so the password prompt consumes the next IDs, or sudo fails once the timestamp expires, and the closing count stays put. Pull the IDs out first, then call sudo loginctl terminate-session from a for-loop whose stdin is still the tty.
KillUserProcesses=no is the other half. A leftover sftp-server or a backgrounded job is enough to pin the session in closing, which is what walks you into the 8192 cap. Setting it to yes reaps those at logout, and it also takes tmux and nohup with them unless they were started under a lingering user manager. That tradeoff is why the Ubuntu default stays no and a sweep of closing sessions is the safer fix.
sudo reads the password from the terminal unless it’s run with -S, so the prompt doesn’t take IDs from the loop’s stdin. The manual says -S reads it “from the standard input instead of using the terminal device”.
The loop does need a terminal, so run the whole loop as root with sudo sh -c '...' when there’s no tty, such as from cron.
The sessions in the source thread had no leader process and no session scope, so KillUserProcesses=yes wouldn’t have cleared them, but it’s a valid setting where leftover processes are what keep sessions in closing.
c-wind
The clear loop is right to skip anything that isn't closing, but sudo is on the wrong side of the pipe. stdin is the session list, so the password prompt consumes the next IDs, or sudo fails once the timestamp expires, and the closing count stays put. Pull the IDs out first, then call sudo loginctl terminate-session from a for-loop whose stdin is still the tty.
KillUserProcesses=no is the other half. A leftover sftp-server or a backgrounded job is enough to pin the session in closing, which is what walks you into the 8192 cap. Setting it to yes reaps those at logout, and it also takes tmux and nohup with them unless they were started under a lingering user manager. That tradeoff is why the Ubuntu default stays no and a sweep of closing sessions is the safer fix.