help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

[Help-bash] Why 'exec' has to be used in with fd<>filename? And the diff


From: Peng Yu
Subject: [Help-bash] Why 'exec' has to be used in with fd<>filename? And the difference between <> and >>?
Date: Tue, 11 Feb 2014 17:28:59 -0600

Hi,

exec fd<>fileName

The example shown at
http://bash.cyberciti.biz/guide/Opening_the_file_descriptors_for_reading_and_writing
is easier to follow that what is in man bash.

   Opening File Descriptors for Reading and Writing
       The redirection operator

              [n]<>word

       causes  the  file  whose name is the expansion of word to be
opened for both reading
       and writing on file descriptor n, or on file descriptor 0 if n
is not specified.  If
       the file does not exist, it is created.

In the above document, I don't see 'exec' should be used. Where is
this documented? Thanks.

Also, what is the benefit of using exec fd<>filename. For example, is
main.sh more efficient than main1.sh (because the file is only opened
once in main.sh)? Thanks.

~/linux/test/bash/man/redirection/<>$ cat.sh main.sh main1.sh
==> main.sh <==
#!/usr/bin/env bash

tmpfile=$(mktemp)
exec 42<>"$tmpfile"

# Write to file
for i in $(seq 3)
do
  echo "$i" >&42
done

# close fd # 3
exec 42>&-
cat "$tmpfile"

==> main1.sh <==
#!/usr/bin/env bash

tmpfile=$(mktemp)

# Write to file
for i in $(seq 3)
do
  echo "$i" >>"$tmpfile"
done

cat "$tmpfile"

-- 
Regards,
Peng



reply via email to

[Prev in Thread] Current Thread [Next in Thread]