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

  • 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.

主站蜘蛛池模板: 常州市| 荆州市| 林西县| 南涧| 武穴市| 瓦房店市| 曲阳县| 赣州市| 桐梓县| 绥芬河市| 东至县| 织金县| 亚东县| 民丰县| 忻州市| 洞口县| 门头沟区| 望奎县| 旌德县| 克什克腾旗| 莱芜市| 旌德县| 繁昌县| 南通市| 卓资县| 六安市| 东台市| 通化县| 阳高县| 新竹市| 崇州市| 闽侯县| 鄯善县| 琼海市| 吕梁市| 康定县| 调兵山市| 鄂温| 开江县| 青海省| 尚志市|