5.11. Using file descriptors

To open and close files using file descriptors use exec. In the following example, I have chosen file descriptor 4, but I could have chosen any number from 4 to 9. This little script does nothing but reads two lines of a stock file and echoes the lines back.

The first line saves the standard input using file descriptor 4 and then opens the file for reading. The next two lines read in two lines of text. The last line closes the standard input using file descriptor 4. The rest of the script echoes out the contents that were read in using the variables line1 and line2.

						$ pg f_desc 
#!/bin/sh 
# f_desc 
exec 4<&0 0<stock.txt 
read line1 
read line2 
exec 0<&4 
echo $line1 
echo $line2 

Here is that little stock file stock.txt: ...

Get Linux and Unix Shell Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.