Data Streams and the UNIX Shell - Redirection and the Here Document
(Page 3 of 4 )
If you do some shell programming, eventually you will meet with situations where you want to print both the output and the errors in the same file. The solution takes two steps. Print the content of the output in a file. For this use, I just presented the redirection. Then redirect the standard error to the standard output.
sort alfa.txt > save.txt 2>&1
Now, we will not see anything on the terminal. Any information the sort command provides will be printed to the save.txt file. From here, we can read it later if all went well. Because we cannot do anything anyway while the command runs, we may as well just start the command line in the background with the & symbol at the end.
sort alfa.txt > save.txt 2>&1 &
Now we can continue our work and see later if the sort was successful. The commands that act like this are logging, and the output file is the log file. You can also use this approach to direct both the error and the output to a further command via the pipe.
The here document is something that you will use if you write shell programs/scripts. With its help, you can redirect the input of the shell script/program into the file where all of this is. The syntax looks like this:
command << NAME_OF_DELIMITER
here you can
write any kind of text
what will be the text
what the script will get as input
NAME_OF_DELIMITER
You can use it with any kind of shell command. The command will use as input all the text it can find from the word after the << until it finds the word again. Here the command will get one end of file signal, it will stop, and the shell can continue further with the command on the next line.
The text between the delimiter words is treated just as if it were surrounded by double quotes. This means that if you include variable names, the shell will replace the variable with its value. You can have any kind of delimiter. However, it is important that in the last line, only that shows, and nothing else. For example, the following script will print out the first argument as the best shell programmer.
#!/bin/bash
echo "The first argument is $1"
echo << DELIMITER
The best shell programmer is $1
DELIMITER
echo "This is already outside of the here document, Bye bye !"