3

I have a command foo that (for reasons we need not go into) needs to have a pty allocated, i.e. foo succeeds but nohup foo fails.

What is the easiest way to allocate a pty when there is not one? screen -D -m foo seems like overkill, an does not return an exit code (which I need). Save for the exit code, it works.

abligh
  • 397

3 Answers3

2

Use expect, e.g.

#!/usr/bin/env expect -f

spawn -noecho ssh localhost "sleep 3; false"
catch wait status
exit [lindex $status 3]
thrig
  • 34,938
  • This gives me /usr/bin/env: ‘expect -f’: No such file or directory. – CMCDragonkai Jan 23 '19 at 02:59
  • @CMCDragonkai some unix have broken env commands so you'll need to on those systems either change to something without a broken env or use the fully qualified path to wherever your vendor puts the expect command. – thrig Jan 23 '19 at 14:56
2

While @thrig's answer would probably work with expect (and I upvoted it), I made a tiny modification to pty.c from Stevens' Advanced Programming in the UNIX® Environment to return the exit code if -r is specified. The result is here. This seems to do the trick with minimal fuss.

abligh
  • 397
1
script /dev/null

is the easiest, most portable solution (though still not available by default on android or busybox).

It works fine even when its stdin and stdout are not ttys.

  • script /dev/null foo would work on BSD (including macOS). On Linux the syntax is script -qc foo /dev/null, as suggested in https://unix.stackexchange.com/a/249726 – Tanz87 Mar 13 '22 at 23:02