22

I have a misbehaving program that I need to call from my script. It exits as soon as it sees something on stdin. Is there a way to close stdin?

5 Answers 5

31

Is there a way to close stdin?

Closing File Descriptors

  • n<&- Close input file descriptor n.

  • 0<&- or <&- Close stdin.

Source Chapter 20. I/O Redirection

1
  • How to do it programmatically? What ASCII codes I must send to stdin to close it? Feb 24 at 12:59
11

Just pipe in a program with no output:

: | misbehaving_program
2
  • Wow, what is this? What does ':' do? May 24, 2019 at 5:47
  • 1
    ":" is an internal command of the shell that does nothing. It lets you introduce comments, or can be used for redirections. For example ": > file" creates an empty file. Or ": |" in this case feeds an empty stream to the command. May 24, 2019 at 7:16
11

Found it, you can close stdin with:

exec 0<&-
7

According to what you say, you might fix your problem by simply

pickyProgram < /dev/null
1

I found myself struggling with the same problem. My solution is derived from the suggestions here, but differ in that instead of closing stdin with exec 0<&- which allows for subshells to continuously use stdin. An example program that you would expect to exit but does not would look like:

exec 0<&-
$(read stdin)

This is because read is spawned inside a subshell inheriting stdin from the parent. If we instead redirect the stdin we get the expected behaviour

exec 0</dev/null
$(read stdin)

This will yield an exit code 1.

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.