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:
cat file-lists.txt |
OR use NA command as follows for the same purpose:
more file-lists.txt |
Sample outputs:
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 ‘1.2.3.4’ and save to a file called spam-log.txt:
# command must be run as root # grep '1.2.3.4' /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 '1.2.3.4' /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 |
Sample outputs:
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>&1 |



4 comment
Thank you. I have been trying to save files for a machine transfer and trying not to duplicate. Wanted lists to compare and had forgotten how.mUch appreciated.
Please add the tee command as well. Useful for interactive commands.
Ok for example i wanna set slapd password under ubuntu 10.04 server
with
sudo slappasswd > testpass
But i can’t see when i put the password , i just need the last line of the command output to be redirected to a new file . how i can make it ???
How can I store output of a command in a text file tab delimited way.