Save Bash Shell Script Output To a File

by on August 14, 2006 · 4 comments· LAST UPDATED August 14, 2009

in , ,

How do I save my bash shell script output to a file?

You can save bash shell script output to a file using the following syntax:
$ ./yourscript.sh > output.txt
$ /path/to/your/script.sh > output.txt

To append output to existing data.txt file, enter:
$ ./yourscript.sh >> data.txt
$ /path/to/your/script.sh >> data.txt

Understanding > and >> Redirection

Before a command is executed, its input and output may be redirected using a special notation interpreted by the shell. Redirection may also be used to open and close files for the current shell execution environment. The following redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right.

Redirecting Output

Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size. The general format for redirecting output is:

[n]> output.txt
command> output.txt
script.sh> output.txt

If the redirection operator is >, and the noclobber option to the set builtin has been enabled, the redirection will fail if the file whose name results from the expansion of word exists and is a regular file. If the redirection operator is >|, or the redirection operator is > and the noclobber option to the set builtin command is not enabled, the redirection is attempted even if the file named by word exists.

Appending Redirected Output

Redirection of output in this fashion causes the file whose name results from the expansion of word to be opened for appending on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created. The general format for appending output is:

[n]>>append.txt
command>> append.txt
script.sh>> append.txt
TwitterFacebookGoogle+PDF versionFound an error/typo on this page? Help us!

{ 4 comments… read them below or add one }

1 Leon September 12, 2011 at 4:05 am

Thanks for the tute, was a good refresher

Reply

2 Andrew October 18, 2011 at 12:30 pm

I’m a noob to the command line. Is there a way to run an interactive script and output to a file? In other words, can the outbut be directed to both the command line and a file?

Reply

3 Jerry Rice November 23, 2011 at 8:52 am

Andrew, yes see the command “tee”.

Reply

4 Yauvaraj Rimal November 5, 2012 at 5:33 am

What i want to know is, Is there any limit on line size of the output while writing output to file?

Reply

Leave a Comment

Tagged as: , , , , , , , , , , ,

Previous Faq:

Next Faq: