The Bash / KSH and POSIX shell provides a file redirection option to redirect the output of commands to a file using the following two operators:
- > is output redirection symbol.
- >> is append output redirection symbol.
Syntax to save the output of a command to a file
The syntax is:
command > filename
Example: Saving the date command output to a file called output.txt
In this example, save the output of date command to a file called output.txt:
$ date > output.txt
Example: Running Unix/Linux command and saving output to a file
Please note that file-lists.txt file is created if it doesn't exist. And if file file-lists.txt file is overwritten if it exits.
Feel free to replace command with the command you want to run on Linux/Unix and filename with the file to which you want to save (direct) the output. For example, run ls command and store its output the file called "file-lists.txt":
ls -l /bin > file-lists.txt
To see the contents of file-list.txt, use cat command as follows:
OR use NA command as follows for the same purpose:
Example: grep text and save to a file
You can use grep command to scan log files and save to a file. In this example, I am going to search/scan a log file called /var/log/httpd/access_log for spammer IP address '188.8.131.52' and save to a file called spam-log.txt:
# command must be run as root # grep '184.108.40.206' /var/log/httpd/access_log > /root/spam-log.txt
If your log file is too large, run a job (grep command) in the background with an ampersand (&) as follows:
# command must be run as root # grep '220.127.116.11' /var/log/httpd/access_log > /root/spam-log.txt &
Syntax to save and append the output of a command to a file
The > operator always overwrite existing output files. To append the output of a command to the same file use >> operator as follows:
command >> filename
In this example run two commands called date and who and save output to the same file called demo.txt:
echo "Test" > demo.txt ## Append to same file ## echo "A log file by $USER on $HOSTNAME" >> demo.txt who >> demo.txt cat demo.txt
Syntax to redirection of both standard error and output to a file
The basic syntax is as follows for redirection of both standard error and output on bash/ksh or POSIX shell:
command-name &>filename ## POSIX syntax ## command-name >cmd.log 2>&1Tweet itFacebook itGoogle+ itPDF itFound an error/typo on this page?