O'Reilly logo

Linux and Unix Shell Programming by David Tansley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required