nsigma
nsigma

Reputation: 101

Can I use fd redirection in bash to input from and output to different files?

My program read and write fd = 3 (for example), I want it read from file1 and write to file2 when running it in bash. Can I use fd redirection to make it?

Something like below, but it's wrong

./prog 3<file1 3>file2

Upvotes: 0

Views: 445

Answers (1)

If what you want is to copy file1 to file2 and file1 is a text file: First open file1 to read from it

exec 3<file1

Then file2 to write to it. Use different fd than the one used for file1

exec 4>file2

Finally you'd like to iterate over file1 like this

while read -u 3 line;  do  echo $line >&4 ; done

In fact it can be executed in a single line

 exec 3<file1 ; exec 4>file2 ; while read -u 3 line;  do  echo $line >&4 ; done

Enjoy!

Upvotes: 1

Related Questions