ThomasReggi
ThomasReggi

Reputation: 59425

Only output a specific file descriptor using bash

The following command redirects fd 2 to /dev/null is it possible to only output 2?

node ./index.js 2>/dev/null

Upvotes: 0

Views: 47

Answers (1)

that other guy
that other guy

Reputation: 123510

In the classical Unix programming model, there is no way to do this. Programs may instead try to sweep over all possible FDs and attempt to close them:

(
  limit=$(ulimit -n)
  # Try to estimate some upper bound if not set
  [ "$limit" = "unlimited" ] && limit=1024
  for ((i=0; i<limit; i++))
  do
    [ "$i" != 2 ] && exec {i}>&-
  done
  exec node ./index.js
)

However, most OS have a way to introspect open FDs. For example, Linux lets you do:

(
  for fd in "/proc/$BASHPID/fd"/*
  do
    fd="${fd##*/}"
    [ "$fd" != 2 ] && exec {fd}>&-
  done
  exec node ./index.js
)

You may wish to keep 0 and 1 open and/or redirected them from/to /dev/null, as some programs don't cope well with stdin and stdout being closed.

Upvotes: 1

Related Questions