Reading from one file and writing to another file

Now we will see how to read from one file and write to another. Let's write the script as follows:

# We are assigning descriptor 3 to in_file.txt 
exec 3< in_file.txt 
# We are assigning descriptor 4 to out_file.txt 
exec 4> out_file.txt 
# We are reading first line of input.txt 
read -u 3 line 
echo $line 
echo "Writing content of in_file.txt to out_file.txt" 
echo  "Line 1 - $line " >&4 
# Closing both the files 
exec 3<&- 
exec 4<&- 

Save the file, give the permission to execute, and run the script as follows:

    $ chmod u+x
    $ echo "Sun is at the centre of Solar System." > in_file.txt
    $ cat in_file.txt

This should produce the following outputs:

    Sun is at the centre ...

Get Learning Linux Shell Scripting - Second Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.