0

In bash, how to execute a command and have its output in an file descriptor? Preferably the file descriptor should be anonymous, not directly visible outside of the script.

I have previously read similar QA's, but unfortunately none match exactly:

VasyaNovikov
  • 3,656

1 Answers1

0

You can use this:

exec 8< <(my-command --key1 --key2)

This puts the output (stdout) of my-command --key1 --key2 into file descriptor 8. It can be used later in the script, or on the same line.

Alternatively, if you don't want to hardcode any specific FD number, and if you're okay with moving the assignment to a separate line, you can use a "variable redirect" (this solution was proposed by Jetchisel and Gordon Davisson below):

exec {my_special_fd}< <(my-command --key1 --key2)
echo "my_special_fd: $my_special_fd"  # prints the FD, likely 10.
cat /dev/fd/"$my_special_fd"

Explanation:

  • The syntax <(command) executes the inner command and puts the result into a file descriptor like /dev/fd/63. This alone is not enough to solve the problem, unfortunately, because you don't control this number AND the results will stop being available as soon as bash goes executing the next line of the script.
  • The syntax 8< my_file open the contents of the file my_file as the file descriptor 8.
  • The syntax exec ... allows you manipulating the file descriptors independently from other commands. If you want a one-liner that uses the FD directly, you can combine everything and use: program-that-expects-fd --fd=8 8< <(inner-command --key1 --key2)
  • The syndax exec {my_var}< ... chooses an unused FD automatically, places the contents on the right side to that FD and assignes the variable my_var to the chosen FD (it's a number).
  • For details, refer to bash's manual, e.g. man bash.
VasyaNovikov
  • 3,656