Mittwoch, 18. April 2012

Bash filedescriptors and IO redirection with exec

The topic is very well covered in my favorite Bash-Scripting Guide. However, in a few examples they used something like the following code:

#!/bin/bash
# read a file line by line and echo it

filename=$1

exec 3<> $filename
while read line <&3
  do
  echo $line
done

exec 3>&-

The line "exec 3<> $filename" redirects the $filename to filedescriptor 3, which is then used as stdin in the next line. This example just uses input from the file, so I wondered why there was a "<>" instead of just "<", which would be sufficient for just reading the file. The reason is simple: Even though for this example it is not needed, the file is not only opened for reading, but also for writing, thus the ">". The last line "exec 3>&-" closes the file again.

We could modify the example to take advantage of the writing:

#!/bin/bash
# read a file line by line and echo it

filename=$1

exec 3<> $filename
while read line <&3
  do
  echo $line
done
echo another line >&3

exec 3>&-

This adds another line to the file given to the script as first argument. Its the "echo another line >&3" ( -- I should probably start using proper code highlighting ).

Keine Kommentare:

Kommentar veröffentlichen