Linux File Descriptors

From Ever changing code

It's an index table from 0..n per process that indicates what files,pipes,sockets the process has open.

File Descriptors 0,1,2 are reserved for OS, for:

  • 0 - STDOUT
  • 1 - STDIN
  • 2 - STDERR

Following script demonstrates FD usage:

echo "File name to read: "
read FILE  # type 'cities.txt', this file must exist

# assign/create FD '5' to a file, what we can refere as a strem to read or write in the future
exec 5<>$FILE   # open a file for read and write (aka open a file handle)
# >  open for write
# <  open for read
# <> open for rw

while read -r CITY; do # read a file line-by-line
  echo "City name: $CITY"
done <&5 # instead redirecting a file value, we redirect a FD for reading '<'
# &<number> - ampersand indicates that it's FD

# Write to a file but instead using a file we use FD for writting '>'
echo "File was read on: $(date)" >&5

# Close FD, otherwise will stay open forever (aka close file handle)
exec 5>&-

File to read

cat > cities.txt << EOF