CHAPTER 17 COOL SHELL TRICKS It s also (Web hosting ratings)

CHAPTER 17 COOL SHELL TRICKS It s also possible to direct the contents of a file back into a command. Take a look at the following: sort < textfile.txt > sortedtext.txt The sort command simply sorts words into alphanumeric order (it actually sorts them according to the ASCII table of characters, which places symbols and numbers before alphabetic characters). Directly after the sort command is a left angle bracket, which directs the contents of the file specified immediately after the bracket into the sort command. This is followed by a right angle bracket, which directs the output of the command into another file. Tip To see a table of the ASCII characters, type man 7 ascii at the command-line prompt. There aren t many instances in day-to-day usage where you ll want to use the left angle bracket. It s mostly used with the text-based mail program (which lets you send e-mail from the shell), and in shell scripting, in which a lot of commands are combined together to form a simple program. REDIRECTING STANDARD ERROR OUTPUT Standard input and standard output are what BASH calls your keyboard and screen. These are the default input and output methods that programs use unless you specify something else, such as redirecting or piping output and input. When a program goes wrong, its error message doesn t usually form part of standard output. Instead, it is output via standard error. Like standard output, this usually appears on the screen. Sometimes, it s very beneficial to capture an error message in a text file. This can be done by redirecting the standard error output. The technique is very similar to redirecting standard output: cdrecord –scanbus 2> errormessage.txt The cdrecord command is used to burn CDs, and with the –scanbus command option, you tell it to search for CD-R/RW drives on the system, something which frequently results in an error message if your system is not properly configured. After the initial command, you see the redirection. To redirect standard error, all you need to do is type 2>, rather than simply >. This effectively tells BASH to use the second type of output: standard error. You can direct both standard output and standard error to the same file. This is done in the following way: cdrecord –scanbus > error.txt 2>&1 This is a little more complicated. The standard output from cdrecord –scanbus is sent to the file error.txt. The second redirect tells BASH to include standard error in the standard output. In other words, it s not a case of standard output being written to a file, and then standard error being added to it. Instead, the standard error is added to standard output by BASH, and then this is written to a file.

Leave a Reply