Write Output To File

By default standard output of a program goes to the screen. For example, the standard output of ls is a list of files and directories in a directory, which is by default shown on the terminal screen. However, it does not need to be. We can redirect the standard output of a program to a file using the > operator.

Make Some Files And Folders

touch config.txt; touch data.csv; touch readme.md; mkdir sales_data; mkdir scripts

Run ls To See Standard Output

ls -l
total 8
-rw-rw-r-- 1 chris chris    0 Jul 26 11:23 config.txt
-rw-rw-r-- 1 chris chris    0 Jul 26 11:23 data.csv
-rw-rw-r-- 1 chris chris    0 Jul 26 11:23 readme.md
drwxrwxr-x 2 chris chris 4096 Jul 26 11:23 sales_data
drwxrwxr-x 2 chris chris 4096 Jul 26 11:23 scripts

Redirect ls’s Standard Output To File

Notice the > operator followed by the file where the standard output will be written.

ls -l > directory_contents.txt

View File’s Contents To See Redirected Standard Output

cat directory_contents.txt
total 8
-rw-rw-r-- 1 chris chris    0 Jul 26 11:23 config.txt
-rw-rw-r-- 1 chris chris    0 Jul 26 11:23 data.csv
-rw-rw-r-- 1 chris chris    0 Jul 26 11:24 directory_contents.txt
-rw-rw-r-- 1 chris chris    0 Jul 26 11:23 readme.md
drwxrwxr-x 2 chris chris 4096 Jul 26 11:23 sales_data
drwxrwxr-x 2 chris chris 4096 Jul 26 11:23 scripts