官术网_书友最值得收藏!

  • Ubuntu 20.04 Essentials
  • Neil Smyth
  • 342字
  • 2021-06-11 17:39:42

9.9 Input and Output Redirection

As previously mentioned, many shell commands output information when executed. By default this output goes to a device file named stdout which is essentially the terminal window or console in which the shell is running. Conversely, the shell takes input from a device file named stdin, which by default is the keyboard.

Output from a command can be redirected from stdout to a physical file on the file system using the ‘>’ character. For example, to redirect the output from an ls command to a file named files.txt, the following command would be required:

$ ls *.txt > files.txt

Upon completion, files.txt will contain the list of files in the current directory. Similarly, the contents of a file may be fed into a command in place of stdin. For example, to redirect the contents of a file as input to a command:

$ wc –l < files.txt

The above command will display the number of lines contained in the files.txt file.

It is important to note that the ‘>’ redirection operator creates a new file, or truncates an existing file when used. In order to append to an existing file, use the ‘>>’ operator:

$ ls *.dat >> files.txt

In addition to standard output, the shell also provides standard error output using stderr. While output from a command is directed to stdout, any error messages generated by the command are directed to stderr. This means that if stdout is directed to a file, error messages will still appear in the terminal. This is generally the desired behavior, though stderr may also be redirected if desired using the ‘2>’ operator:

$ ls dkjfnvkjdnf 2> errormsg

On completion of the command, an error reporting the fact that the file named dkjfnvkjdnf could not be found will be contained in the errormsg file.

Both stderr and stdout may be redirected to the same file using the &> operator:

$ ls /etc dkjfnvkjdnf &> alloutput

On completion of execution, the alloutput file will contain both a listing of the contents of the /etc directory, and the error message associated with the attempt to list a non-existent file.

主站蜘蛛池模板: 宁陵县| 嘉定区| 临安市| 水富县| 曲靖市| 花垣县| 宁海县| 江达县| 新乡县| 泰来县| 长治县| 喀喇| 杭州市| 眉山市| 鸡西市| 唐河县| 武鸣县| 仲巴县| 积石山| 荣成市| 泸州市| 林周县| 平遥县| 迁安市| 安吉县| 南汇区| 巴林左旗| 潼关县| 开鲁县| 恩施市| 千阳县| 华阴市| 米林县| 安龙县| 六枝特区| 民勤县| 哈密市| 思茅市| 成武县| 太谷县| 名山县|