4

I have a simple script I am building that monitors the auth.log for su/ssh sessions being opened. If it sees a session opened using su or ssh it sends a push message using Gotify. I have tested the Gotify command by putting it in its own script and running it and it works but as soon as it is in the while loop it just hangs. I have found a fix from this question Shell script hangs on mail command by redirecting the input from /dev/null to the gotify command, but I am unsure why I need to do it in this particular instance and not when I use it in other scripts (I have a few other scripts where i use gotify without the redirect).

The script is:

#! /bin/bash
pipe=$(mktemp -u)
mkfifo "${pipe}"
log="/var/log/auth.log"

trap "rm -f $pipe" EXIT

tail -f $log >> $pipe &

while read line;
  do
    aryLine=(${line})
    if [[ "${aryLine[@]:5:3}" =~ "pam_unix("(su|sshd)":session): session opened" ]]; then
      echo "session opened for ${aryLine[@]:10:4}"
     /usr/bin/gotify push -p 3 --title "login" "login from ${aryLine[10]}" < /dev/null
    fi
done < $pipe

I am at a loss why I need the /dev/null to stop the script hanging when using gotify within this particular while/if loop and any help understanding will be appreciated. The code below works and spams my gotify just fine:

#! /bin/bash
while true; do
  if true; then
    /usr/bin/gotify push -p 3 --title "login" "login from ${aryLine[10]}"
  fi
done

I am using Debian Bullseye.

3
  • 1
    Please paste your script at shellcheck.net.
    – Cyrus
    Apr 9, 2023 at 16:48
  • Related: SSH causes while loop to stop Apr 9, 2023 at 22:54
  • @Cyrus Thanks, that's a handy site. I have used them before for PHP, Javascript, and Regex, but didn't even think to search for one for bash scripts.
    – Èl Sea
    Apr 10, 2023 at 9:10

1 Answer 1

4

You need the /dev/null redirection because the whole while .. do .. done < $pipe compound command is set to read from the pipe, including the gotify command. The gotify command probably tries to read from its standard input (which is now a pipe) and blocks until it reaches end-of-file, which will only happen when tail terminates. </dev/null redirection allows you to run gotify disconnected from the pipe, so that it doesn't try to read from it.

I believe gotify behaves this way because it allows you to do things like:

echo "my message" | gotify push

It has to try reading its standard input to make this feature work.

1
  • ahh ok that makes sense why the test while loop worked as it wasn't redirected like the other one is.
    – Èl Sea
    Apr 10, 2023 at 5:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .