How the below shell redirection works ? Appears to be complicated to understand the order of execution. Any easy explanation ?
uuencode host-file < host-file >encodedfile
How the below shell redirection works ? Appears to be complicated to understand the order of execution. Any easy explanation ?
uuencode host-file < host-file >encodedfile
uuencode
is the command.host-file
is its argument.< host-file
redirects the file to the standard input of the command.>encodedfile
redirects output of the command to the file.When a console program is launched, it opens three standard file descriptors:
0 STDIN
1 STDOUT
2 STDERR
Normally the STDIN filehandle reads from the terminal input (i.e. the keyboard). But when the
<
redirection is used, input is read from that file instead. Likewise, STDOUT usually writes to the terminal, but when>
is used, output is written to that file instead.STDERR can similarly be redirected by using
2>
. You might also see STDERR being redirected to the same place as STDOUT by using2>&1
.uuencode host-file < host-file >encodedfile
Let's break this down into 4 parts:
uuencode
is the name of the command to run. The shell searches the PATH environment variable ($PATH) and looks for an executable file nameduuencode
in each directory in the PATH. In a standard install, this will be/usr/bin/uuencode
. The uuencode program takes a binary file and turns it into text in a special format so it can be sent over a network that can't handle non-ascii characters.host-file
is the command line argument touuencode
. Theuuencode
command needs one argument so that it can put the name of the file in the encoded version. The first line of the encoded file will look something like this:begin 644 host-file
< host-file
is the shell using a file namedhost-file
as standard input (stdin) for theuuencode
process. So whenuuencode
reads some bytes of input, instead of coming from your keyboard, they come from that file.>encodefile
is the shell using a file namedencodedfile
as standard output (stdout). Thus, whenuuencode
writes some output, instead of going to your screen, it goes to that file.There is not really an order of execution, since only one command,
uuencode
, is being executed. If you want technical details, read on.Behind the scenes, the shell calls
fork()
, then the child process opens thehost-file
file for reading, opens theencodedfile
file for writing, and callsexec()
, which replaces the child process (a copy of the shell process) with theuuencode
process. The child process then becomesuuencode
, with the input file descriptor (a way the operating system keeps track of open files) set to that ofhost-file
and the output file descriptor set to that ofencodedfile
.