Bash/Scripting/File descriptors

Aus SchnallIchNet
Wechseln zu: Navigation, Suche

Misc infos

Bash handles several filenames specially when they are used in redirections, as described in the following table:

/dev/fd/fd
    If fd is a valid integer, file descriptor fd is duplicated. 
/dev/stdin
    File descriptor 0 is duplicated. 
/dev/stdout
    File descriptor 1 is duplicated. 
/dev/stderr
    File descriptor 2 is duplicated. 

not listed here:

/dev/udp/...
/dev/tcp/...

you can find these here: Network-Sockets


Playing with several file descriptors

Here is a small example of a shell script using several file descriptors. This script reads a file with the following columns "ip_address trafic_in trafic_out", and writes two files trafic_in and trafic_out.

#!/bin/bash

# open the two output files
exec 6>/tmp/trafic_in.dat
exec 7>/tmp/trafic_out.dat

#open the file containing the data for input.
exec 8</tmp/all_trafic.dat

# data processing
grep -v '^#' <&8 | while read line
do
    set - $(echo $line)
    echo "${1}	${2}" >&6
    echo "${1}	${3}" >&7
done

#close the file descriptors
exec 6<&-
exec 7<&-

Playing with stdin

exec < /path/to/textfile

while read line; do
   echo $line
   [... whatever ...]
done

Open FD's for network-sockets

bash handles two special "files" which are used to open network sockets. the manual page of bash says:

              /dev/tcp/host/port
                     If  host  is  a  valid  hostname or Internet
                     address, and port is an integer port  number
                     or service name, bash attempts to open a TCP
                     connection to the corresponding socket.
              /dev/udp/host/port
                     If host is  a  valid  hostname  or  Internet
                     address,  and port is an integer port number
                     or service name, bash attempts to open a UDP
                     connection to the corresponding socket.

well actually you'll not going to find directories named /dev/tcp and /dev/udp (unless you create them, but don't).they are valid only in bash.let's suppose that you have port 80 (www) open. we could improvise a simple web browser in bash by opening a tcp connection like this:

$ exec 3<> /dev/tcp/127.0.0.1/80

now descriptor 3 points to port 80 of our machine (if you're connected to the Internet you can open sockets to remote hosts by simply providing their hostname/address and port) lets send the http request:

$ echo "GET /index.html HTTP/1.0" 1>&3
$ echo 1>&3

now the result is waiting for us to get it:

$ while read 0<&3; do echo $REPLY; done

this reads up a line until EOF and prints it on screen

now I suppose you know what `network programming in bash' is. but if you're new to it I recommend you to read the manual page first then guides like this.

Network programming in bash is cool. Now write something useful!