0

In the book Modern Operating System, the author explained that if the shell script has two commands, p1 and p2 and each takes turn writing into a file x, the position where p1 finishes will be remembered by p2, as they are using the same open-file-description table. I test this with a simple script.

#!/bin/bash
echo 11 > a.txt
echo 12 > a.txt

It turns out that the second command overwrites the file completely. Anything wrong with the script or the implementation?

  • 1
    Operation `>` (re-) **writes** the file, operation `>>` **appends** to the file. Probably, you want to use the latter one: `echo 12 >> a.txt`. – Tsyvarev Feb 19 '21 at 18:06
  • First edition was 1992 and ast was a Linux basher then. – stark Feb 21 '21 at 22:21

1 Answers1

0

Yes, each echo command opens the file (and deletes the existing contents), writes to the file, and then closes it. There's no sharing at all.

To share an open file description, try this:

#!/bin/bash
exec 123>a.txt # open file descriptor 123 to a.txt (note that you have to choose one, bash won't choose a number)
exec 124>&123 # open file descriptor 124 as a copy of 123 (same file description)

# now we have two file descriptors pointing to the same file description
echo 11 >&123 # write to descriptor 123
echo 12 >&124 # write to descriptor 124

exec 123>&- # close file descriptor 123
exec 124>&- # close file descriptor 124

Of course, we're still not using two processes here, just two descriptors in one process

user253751
  • 57,427
  • 7
  • 48
  • 90