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.


Use expect, e.g.

#!/usr/bin/env expect -f

spawn -noecho ssh localhost "sleep 3; false"
catch wait status
exit [lindex $status 3]
  • This gives me /usr/bin/env: ‘expect -f’: No such file or directory. – CMCDragonkai Jan 23 at 2: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 at 14:56

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.