msgbartop
Tips and Tricks site for advanced HP-UX Engineers
msgbarbottom

13 Nov 19 Using File Descriptors other than stdin/stdout/stderr in Shell Scriptings

For a longish ime, I had to jump through major hoops to script around the issue of my standard input getting clobbered when inside a loop that was iterating over something that coming from stdin. I don’t have an exact example that recreates the issue but something like this would generate lots of headaches:

cat <some file> | awk '{<some fancy awk-type hingys>}' | \
  while read entry; do
    bla; bla; bla
    some_command_here_that_would_whack_stdin
    bla; bla; bla
  done

Sorry I cannot provide an actual snippet of code to recreate the issue but what I would find in these situations is that my loop would end after one iteration (when I knew there should have been a lot more) and I coudn’t figure out why which made me haz a sad.

Well, I found a way to steer clear of all that by assigning a <some file> to a file descriptor different from stdin. To wit:

exec 3< /path/to/file
while read entry <&3; do
   bla; bla; bla
   some_command_here_that_would_whack_stdin
   bla; bla; bla
done

There are no doubt other ways to solve this conundrum but this is the way I have avoided it for quite some time now. Of course, make sure you do not associate a file with file descriptors 0,1,2 (unless you are quite sure that is what you want to do!).

Leave a Comment

You must be logged in to post a comment.

WhatsApp chat