I think I got something wrong in my code to reproduce the cron problem:

true | setsid zsh -c 'ps -o tty $$; read -k1 && echo 1'

ps does not shows a tty, but read works correctly...

Pier Paolo Grassi


Il giorno sab 7 gen 2023 alle ore 18:21 Pier Paolo Grassi <pierpaolog@gmail.com> ha scritto:
Thanks, but i don't _always_ redirect stdin.
i wonder how is ps getting the tty (it displays an ? when there is no tty for the process)
I suppose it uses /proc, but couldn't find a reference or the info exploring the /proc fs by myself.
for now I am asking directly ps:
[[ "$(ps h -o tty $$)" != "?" ]] && ...

Pier Paolo Grassi


Il giorno sab 7 gen 2023 alle ore 14:44 Roman Perepelitsa <roman.perepelitsa@gmail.com> ha scritto:
On Sat, Jan 7, 2023 at 2:32 PM Pier Paolo Grassi <pierpaolog@gmail.com> wrote:
>
> Hello, I have a script that asks to create a target dir if it doesn't exist.
> to that extend I inserted an
> read -k1
> in the script.
> To be able to ask the user for confirm even when the script stdin is connected to a pipe I did
> read -k1 < /dev/tty

Note that this redirect doesn't affect `read -k1`. It'll read from the
terminal either way.

You can do something like this in your script:

  if [[ -r $TTY ]]; then
    read -k1
  else
    read -k1 -u0
  fi

There is a corner case when you log in as root and then su to a
non-privileged user. $TTY won't be readable even though the process
has a TTY. Since you are redirecting stdin anyway, this corner case
shouldn't affect you.

Roman.