Difference between revisions of "Opening the file descriptors for reading and writing"

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search
(Created page with 'Bash supports the following syntax to open file for both reading and writing on file descriptor: <pre>exec fd<>fileName</pre> * File descriptor 0 is used if fd is not specified. …')
 
m (Text replacement - "</source>" to "</syntaxhighlight>")
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
 +
{{navigation
 +
|previous=Closes the file descriptor (fd)
 +
|next=Reads from the file descriptor (fd)}}
 +
 
Bash supports the following syntax to open file for both reading and writing on file descriptor:
 
Bash supports the following syntax to open file for both reading and writing on file descriptor:
 
<pre>exec fd<>fileName</pre>
 
<pre>exec fd<>fileName</pre>
Line 6: Line 10:
 
==Example==
 
==Example==
 
Create a shell script called fdreadwrite.sh
 
Create a shell script called fdreadwrite.sh
<source lang="bash">#!/bin/bash
+
<syntaxhighlight lang="bash" >#!/bin/bash
 
FILENAME="/tmp/out.txt"
 
FILENAME="/tmp/out.txt"
 
# Opening file descriptors # 3 for reading and writing
 
# Opening file descriptors # 3 for reading and writing
Line 16: Line 20:
 
echo "Fear is the path to the dark side. Fear leads to anger. " >&3
 
echo "Fear is the path to the dark side. Fear leads to anger. " >&3
 
echo "Anger leads to hate. Hate leads to suffering." >&3
 
echo "Anger leads to hate. Hate leads to suffering." >&3
echo "--- Zoda" >&3
+
echo "--- Yoda" >&3
  
# Read the same file using while loop
+
# close fd # 3
while IFS= read -u 3 -r line
+
exec 3>&- </syntaxhighlight>
do
 
  echo $line
 
done
 
  
# close fd # 3
 
exec 3>&- </source>
 
 
[[Category:Redirection]][[Category:Commands]]
 
[[Category:Redirection]][[Category:Commands]]
 +
 +
{{navigation
 +
|previous=Closes the file descriptor (fd)
 +
|next=Reads from the file descriptor (fd)}}

Latest revision as of 22:50, 29 March 2016

← Closes the file descriptor (fd)HomeReads from the file descriptor (fd) →

Bash supports the following syntax to open file for both reading and writing on file descriptor:

exec fd<>fileName
  • File descriptor 0 is used if fd is not specified.
  • If the file does not exist, it is created.
  • This syntax is useful to update file.

Example

Create a shell script called fdreadwrite.sh

#!/bin/bash
FILENAME="/tmp/out.txt"
# Opening file descriptors # 3 for reading and writing
# i.e. /tmp/out.txt
exec 3<>$FILENAME

# Write to file
echo "Today is $(date)" >&3
echo "Fear is the path to the dark side. Fear leads to anger. " >&3
echo "Anger leads to hate. Hate leads to suffering." >&3
echo "--- Yoda" >&3

# close fd # 3
exec 3>&-

← Closes the file descriptor (fd)HomeReads from the file descriptor (fd) →