Difference between revisions of "Tutorial5: Redirection"

From CDOT Wiki
Jump to: navigation, search
(Redirection (Standard Input, Standard Output, Standard Error))
(Redirection (Standard Input, Standard Output, Standard Error))
Line 68: Line 68:
 
'''Standard input''' ('''stdin''') is a term which describes from where a command receives input.<br>
 
'''Standard input''' ('''stdin''') is a term which describes from where a command receives input.<br>
 
This would apply only to Unix/Linux commands that accept stdin input (like ''cat'', ''more'', ''less'', ''sort'', ''grep'', ''head'', ''tail'', etc.).<br>
 
This would apply only to Unix/Linux commands that accept stdin input (like ''cat'', ''more'', ''less'', ''sort'', ''grep'', ''head'', ''tail'', etc.).<br>
 +
  
 
''Examples:''
 
''Examples:''
Line 76: Line 77:
 
<table align="right"><tr><td>[[Image:stdout-symbol-1.png|thumb|right|250px|The '''standard input''' ('''stdin''') symbol with one greater than sign overwrites existing file content with command output]]</td><td>[[Image:stdout-symbol-2.png|thumb|right|250px|The '''standard input''' ('''stdin''') symbol  with two greater than signs add command's output to bottom of existing file's contents.]]</td></tr></table>
 
<table align="right"><tr><td>[[Image:stdout-symbol-1.png|thumb|right|250px|The '''standard input''' ('''stdin''') symbol with one greater than sign overwrites existing file content with command output]]</td><td>[[Image:stdout-symbol-2.png|thumb|right|250px|The '''standard input''' ('''stdin''') symbol  with two greater than signs add command's output to bottom of existing file's contents.]]</td></tr></table>
 
'''Standard output''' ('''stdout''') describes where a command sends it's output.<br>In the examples below, output from a command is sent to the '''monitor''', unless it is sent to a '''regular file'''.<br>We will discuss another redirection technique called '''pipelines''' later.
 
'''Standard output''' ('''stdout''') describes where a command sends it's output.<br>In the examples below, output from a command is sent to the '''monitor''', unless it is sent to a '''regular file'''.<br>We will discuss another redirection technique called '''pipelines''' later.
 +
  
 
''Examples:''
 
''Examples:''

Revision as of 12:17, 25 January 2020

REDIRECTION: STANDARD INPUT / STANDARD OUTPUT / STANDARD ERROR


Main Objectives of this Practice Tutorial

  • Define the terms Standard Input (stdin), Standard Output (stdout), and Standard Error (stderr)
  • Understand the purposes of redirection symbols >, >>, 2>, 2>>, and |
  • Define the following file manipulation commands: cut, tr, and wc
  • Define the term pipeline command and explain how a pipeline command functions
  • Define the term filter and how it relates to redirection using pipeline commands
  • Use the semicolon ";" and grouping "( )" symbols issue multiple Unix / Linux commands in a single line
  • Use the backslash "\" symbol to spread-out long Unix/Linux commands over multiple lines


Tutorial Reference Material

Course Notes
Linux Command / Shortcut Reference
YouTube Videos
Course Notes:


Redirection

Multiple Commands

Redirection Filters Brauer Instructional Videos:

KEY CONCEPTS

Redirection (Standard Input, Standard Output, Standard Error)

... standard streams are preconnected input and output communication channels between a computer program and its environment when it begins execution. The three input/output (I/O) connections are called standard input (stdin), standard output (stdout) and standard error (stderr). Originally I/O happened via a physically connected system console (input via keyboard, output via monitor), but standard streams abstract this. When a command is executed via an interactive shell, the streams are typically connected to the text terminal on which the shell is running, but can be changed with redirection or a pipeline.

Reference: https://en.wikipedia.org/wiki/Standard_streams

The standard input (stdin) symbol that describes where a Unix/Linux command receives input

Standard input (stdin) is a term which describes from where a command receives input.
This would apply only to Unix/Linux commands that accept stdin input (like cat, more, less, sort, grep, head, tail, etc.).


Examples:

tr 'a-z' 'A-Z' < words.txt
cat < abc.txt
sort < xyz.txt


The standard input (stdin) symbol with one greater than sign overwrites existing file content with command output
The standard input (stdin) symbol with two greater than signs add command's output to bottom of existing file's contents.

Standard output (stdout) describes where a command sends it's output.
In the examples below, output from a command is sent to the monitor, unless it is sent to a regular file.
We will discuss another redirection technique called pipelines later.


Examples:

ls -l
ls -l > detailed-listing.txt
ls /bin >> output.txt

The standard error (sterr) symbol with one greater than sign overwrites existing file content with command's error message.
The standard error (stderr) symbol with two greater than signs add command's error message to bottom of existing file's contents.

Standard Error (stderr) describes where a command sends it's error messages.
In the examples below, error messages from a command are sent to a file or are redirected to a file that acts as a "garbage can".

Examples (remember, Unix/Linux is case sensitive and issuing PWD in caps will generate an error message):

PWD
PWD 2> error-message.txt
PWD 2 >> error-messages.txt
PWD 2> /dev/null

Additional File Manipulation Commands

There are some additional regular file manipulation commands that you can use with redirection
(in addition to the other regular file manipulation commands introduced in week 2).

These commands are displayed in the table below:

Linux CommandPurpose
cutUsed to extract fields and characters from records. The option -c option is used to cut by a character or a range of characters. The -f option indicates the field number or field range to display (this may require using the -d option to indicate the field separator (delimiter).

Examples:
cut -f2 filename - extract 2nd field from all records in file, using tab as delimiter (default)
cut -d' ' -f2,5 filename - extract 2nd and 5th field, using space as delimiter
cut -d' ' -f1-3,5 filename - extract 1st through 3rd and 5th fields, using space as delimiter
cut -c3-5 filename - extract 3rd to 5th characters
trUsed to translate characters to different characters.

Examples:
tr a A < filename - translate all characters "a" to "A"
tr "[a-z]" "[A-Z]" < filename - translate lowercase "a" through "z" to uppercase
tr "a-z" "A-Z" < filename - translate lowercase "a" through "z" to uppercase, different syntax (non-System V)
tr ':' ' ' < filename - translate all colons to spaces
tr ' ' '\n' < filename - translate all spaces to newline characters
tr 'abc' 'A' < filename - translate 'a', 'b', and 'c' to 'A', the last character in the "to" string repeats
wcDisplays various counts of the contents of a file.

Examples:
wc -l filename - displays number of lines in file
wc -c filename - displays number of characters in file
wc -w filename - displays number of words in fil


The /dev/null file (sometimes called the bit bucket or black hole) is a special system file
that discards all data written into it. This is useful to discard unwanted command output.

Example:

find / -name "tempfile" 2> /dev/null

Piping (Using Pipes)

A pipeline command sends a command's standard output directly to standard input of other command(s) without having to create temporary files.

Pipeline Command: Having commands send their standard output directly to standard input of other commands without having to use temporary files.

A few simple commands can be combined to form a more powerful command line.


Pipes that are used in a pipeline command are represented by the | symbol.

Commands to the right of the pipe symbol are referred to as filters. They are referred to as filters since those commands are used to modify the stdin that was sent from the previous command. Many commands can be "piped" together, but these commands (filters) must be chained in a specific order, depending on what you wish to accomplish

Examples:
ls -al | more
ls | sort -r
ls | sort | more
ls -l | cut -d" " -f2 | tr 'a-z' 'A-z"
ls | grep Linux | head -5
head -7 filename | tail -2


The tee utility can be used to split the flow of information. For example to save in a file as well as display on a screen.
(Image licensed under cc)

The tee utility can be used to split the flow of information. The tee option -a can be used to add content to the bottom of an existing file as opposed to overwriting the file's previous contents.

The reason for the name "tee" is that the splitting of the flow of information resembles a capital T.

Examples: ls | tee unsorted.txt | sort
ls | grep Linux | tee matched.txt | more
ls | head -5 | tee -a listing.txt


Multiple Commands Using Semicolon, Grouping, and Backquotes

Besides piping, there are other ways that multiple commands may be placed in one line:
commands may be separated by semi-colons.


Example:

sleep 5; ls (Note: each command will be executed when the previous command has terminated)


Multiple commands can also be grouped by using parentheses.


Example:

(echo "Who is on:"; w) > whoson


Commands may also be split over multiple lines, making it easier (for humans) to interpret a long command.
You can add a quote or "escape" the newline character at the end of a line, to get rid of the special meaning
of newline (to end a command line)


Example:

echo "This will be split over multiple \
lines. Note that the shell will realize \
that a pipe requires another command, so \
it will automatically go to the next line" |tr '[a-z]' '[A-Z]'


INVESTIGATION 1: BASICS OF REDIRECTION


In this section, you will learn how to redirect standard input, standard output and standard error when issuing Unix / Linux commands.


Perform the Following Steps:

  1. Login your matrix account and issue a command to confirm you are located in your home directory.

  2. Issue the following Linux command to create the directory: mkdir ~/redirect

  3. Change to the ~/redirect directory and confirm that you changed to that directory.

  4. Use a text editor to create a file in your current directory called data.txt and enter the following text displayed below:

    This is line 1
    This is line 2
    This is line 3


  5. Save editing changes and exit the text editor.

  6. Issue the following Linux command: tr 'a-z' 'A-Z' < data.txt

    What this command do?

  7. Issue the following Linux command: tail -2 data.txt > output.txt

    What does this command do? Check the contents of the output.txt file to confirm.

  8. Issue the following Linux command: tail -2 > output2.txt < data.txt

    Why does this command render the same results as the previous command?
    Try explaining how the command works in terms of stdin and then stdout.

  9. Issue the following Linux command to create a file: cat > output3.txt

  10. Enter the follow text displayed below:

    This is the file output3.txt

  11. Press ctrl-d to exit the command.

  12. Issue the cat command to view the contents of the file: output3.txt

  13. Issue the following Linux command: cp ~murray.saul/uli101/cars .

  14. Issue the cat command to view the contents of the cars file.

  15. Issue the following Linux command: cut -c1-10 uli101/cars

    What did this command do?

  16. Issue the following Linux command: cut -f5 uli101/cars > field5.txt

    What did this command do?

  17. Issue the following Linux command: cut -f1-3 uli101/cars > field123.txt

    What did this command do?

  18. Issue the following Linux command: cut -f1,5 uli101/cars > field15.txt

    What did this command do?

  19. Issue the following Linux command: wc cars > count1.txt

    What information does the count1.txt file contain?

  20. Issue the following Linux command: wc cars > count2.txt

    What information does the count2.txt file contain?

  21. Issue the following Linux command: ls -l > listing.txt

    What information does the count2.txt file contain?

  22. Issue the following Linux command: pwd > listing.txt

    What happenned to the original contents of the file called listing.txt?

  23. Issue the following Linux command (use 2 greater-than signs): date >> listing.txt

    What information does the listing.txt file contain?

  24. Issue the following Linux command: cat listing.txt cars murray 2> result.txt

    What information does the result.txt file contain?

  25. Issue the following Linux command: cat listing.txt cars murray > myoutput.txt 2> result.txt

    What is displayed on the monitor? what do those files contain?


The problem with using redirection to create files, you have these files taking up space, which requires you remove them. In the next investigation, you will be learning how to issue pipeline commands which can provide information by issuing several Linux commands without creating temporary files.

INVESTIGATION 2: REDIRECTION USING PIPES

In this section, you will learn to issue pipeline commands and learn how to perform tasks
using Linux commands with or without the generation of temporary files.


Perform the Following Steps:

  1. Confirm you are located in the ~/redirect directory.

  2. Issue the following Linux command to remove all files in your redirect directory: rm *

    NOTE: You will be issuing a pipeline command which will use the pipe symbol "|" that will send the stdout from a command as stdin into another command.

  3. Issue the follow Linux pipeline command: ls /bin | more

    What happened?

  4. Issue the following Linux pipeline command: ls /bin | who

    What happened? Why is the result different than antipated?
    Pipe-diagram-1.png


    NOTE: When issuing pipeline commands, commands to the right of the pipe symbol must be designed to accept stdin. Since the who command does not, an error message was displayed.

  5. Issue the following Linux command: cp /bin/?? > listing.txt

  6. Issue the following Linux command: sort listing.txt

  7. Issue the following Linux command to remove the listing file: rm listing.txt

  8. Issue the following Linux pipeline command: ls /bin/?? | sort

    You should notice that the output from this pipeline command is the same output from the command you issued in step #6

  9. Issue the ls command.

    You should notice that no files have been created. Let's get practice issuing more pipeline commands using commands (previously learned or new) to be used as filters.

  10. Issue the following Linux pipeline command: ls /bin/?? | sort -r | head -5

    What did you notice?

  11. Issue the following Linux pipeline command: ls /bin/???? | sort -r | grep r | tail -2

    What did you notice?

  12. Issue the following Linux pipeline command: ls /bin/???? | sort -r | grep r | cut -1-

  13. Issue the following Linux pipeline command: ls /bin/???? | tee unsorted.txt | sort -r | tee sorted.txt | tee unmatched.txt | grep r | tail -2

    What did you notice?

  14. Check the files that were created to see how the tee command was used in the previous pipeline command.

  15. Change to your home directory.

  16. Issue the following Linux command to remove the ~/redirect directory and its contents: rm -r ~/redirect


In the next investigation, you will learn various techniques to issue multiple Linux commands on the same line, or long Linux commands over multiple lines.

INVESTIGATION 3: ISSUING MULTIPLE UNIX/LINUX COMMANDS

In this section, you will learn how to issue multiple Unix / Linux commands in a single line or over multiple lines.


Perform the Following Steps:

  1. Confirm you are located in your home directory.

  2. Issue the following Linux commands (using semicolon to separate each command): cal;pwd;date

    Note the from the output the order of how each of those commands were processed.

  3. Issue the following Linux commands: (cal;pwd;date)

    Was there any difference in the output of this command as opposed to the previous command?

  4. Issue the following Linux pipeline command (using \ at the end of most lines):
    echo "This will be split over multiple \
    lines. Note that the shell will realize \
    that a pipe requires another command, so \
    it will automatically go to the next line" |tr '[a-z]' '[A-Z]'


    Did the command work? What does this command do?

  5. After you complete the Review Questions sections to get additional practice, then work on your online assignment 2 and complete section3 labelled: Redirection and Pipes.



LINUX PRACTICE QUESTIONS

The purpose of this section is to obtain extra practice to help with quizzes, your midterm, and your final exam.

Here is a link to the MS Word Document of ALL of the questions displayed below but with extra room to answer on the document to simulate a quiz:

https://ict.senecacollege.ca/~murray.saul/uli101/uli101_week5_practice.docx

Your instructor may take-up these questions during class. It is up to the student to attend classes in order to obtain the answers to the following questions. Your instructor will NOT provide these answers in any other form (eg. e-mail, etc).

When answering Linux command questions, refer to the following Inverted Tree diagram. The linux directory is contained in your home directory. Assume that you just logged into your Matrix account. Directories are underlined.

Week5-dir.png











Review Questions:

  1. Write a single Linux command to provide a detailed listing of all files in the /bin directory, sending the output to a file called listing.txt in the “projects” directory (append output to existing file and use a relative pathname)
  2. Write a single Linux command to redirect the stderr from the command:
    cat a.txt b.txt c.txt to a file called error.txt contained in the “assignments” directory. (overwrite previous file’s contents and use only relative pathnames)
  3. Write a single Linux command: cat ~/a.txt ~/b.txt ~/c.txt and redirect stdout to a file called “good.txt” to the “tests” directory and stderr to a file called “bad.txt” to the “tests” directory. (overwrite previous contents for both files and use only relative-to-home pathnames).
  4. Write a single Linux command to redirect the stdout from the command:
    cat a.txt b.txt c.txt to a file called wrong.txt contained in the “projects” directory and throw-out any standard error messages so they don’t appear on the screen (append output to existing file and use only relative pathnames).

  5. Write a single Linux pipeline command to display a detailed listing of the “projects “directory but pause one screen at a time to view and navigate through all of the directory contents. Use a relative-to-home pathname.
  6. Write a single Linux pipeline command to display the sorted contents (in reverse alphabetical order) of the “linux” directory. Use a relative pathname.
  7. Assume that the text file called “.answers.txt” contains 10 lines. Write a single Linux pipeline command to only displays lines 5 through 8 for this file. Use only relative pathnames.
  8. Write a single Linux pipeline command to only display the contents of the “assignments” directory whose filenames match the pattern “murray” (both upper or lowercase). Use an absolute pathname.
  9. Write a single Linux pipeline command to display the number of characters contained in the file called “.answers.txt”. Use a relative-to-home pathname.
  10. Write a single Linux pipeline command to display the number of lines contained in the file called “questions.txt”. Use a relative pathname.
  11. Write a single Linux pipeline command to display only the first 10 characters of each filename contained in your current directory. Also, there is will be a lot of output, so also pause at each screenful so you can navigate throughout the display contents. Use a relative pathname.
  12. Create a table listing each Linux command, useful options that were mentioned in this tutorial for the following Linux commands: cut , tr , wc , and tee.