# Print Bash command output to a file

This post shows how to redirect command output or static text to a file.

## The redirection operators `>` and `>>`

Write a string to a file, replacing its contents:

```shell
$ echo "hello" > foo.txt
```

Use `>>` to append instead:

```shell
$ echo "hello" >> foo.txt
```

Append command output into a file:

```shell
$ ls >> foo.txt
```

Use `cat` to check the result:

```shell
$ cat foo.txt
```

A real-world example is adding [fish](/how-to-install-and-use-fish-shell) to
your available shells:

```shell
$ command -v fish | sudo tee -a /etc/shells
```

## The tee command

You can also pipe into the `tee` command:

```shell
$ command -v fish | tee foo.txt
```

Use the `-a` flag to append:

```shell
$ command -v fish | tee -a foo.txt
```

## The paste command

This command outputs filenames separated by commas:

```shell
$ ls -1 | paste -sd "," -
foo.txt,bar.txt,baz.txt
```

It breaks down to:

`-1`

(The numeric digit one.) Force output to be one entry per line. This is the
    default when output is not to a terminal.

`-s`

Concatenate all of the lines of each separate input file in command line
    order. The newline character of every line except the last line in each
    input file is replaced with the tab character, unless otherwise specified by
    the -d option.

`-d`

Use one or more of the provided characters to replace the newline characters
    instead of the default tab.

`-`

The hyphen at the end means standard input.

To keep one filename per line, skip `paste`:

```shell
$ ls -1 > foo.txt
```

If you want to limit the results, globs can be used in normal fashion. This
lists only jpg files:

```shell
$ ls -1 *.jpg | paste -sd "," - > jpegs.txt
```

Or jpgs and pngs:

```shell
$ ls -1 *.{jpg,png} | paste -sd "," - > bitmaps.txt
```

## Make a CSV

A primitive receipt management system. Name your receipts in this format:

```
yyyy-mm-dd,recipient,price,item,reference,.ext
```

An example file might look like this:

```
2015-01-01,DigitalOcean,10,server,165496-21,.pdf
```

Then print them out into a file:

```shell
$ ls -1 *.pdf > receipts-2015.csv
```

Then open it in a spreadsheet application.

![Screenshot 2015-03-03 09.47.13](/images/Screenshot-2015-03-03-09.47.13.png)
