Skip to main content

Command Palette

Search for a command to run...

Writing to file using bash redirection

Updated
1 min readView as Markdown
Writing to file using bash redirection

Hello.

In this article, we are going to write to a file using a file descriptor.

Let's go!

The file we want to work with is animals.txt:

$ cat animals.txt
dog
horse
cow
chipmunk

First we have to tell bash to set up the redirection required.

$ exec 4>>animals.txt

This opens animals.txt for writing and assigns file descriptor 4. Note the use of >> instead of > so we can append to the file.

Now let's try adding a line to animals.txt.

$ echo foobar >&4

This writes foobar to file descriptor 4 which is the same as writing to animals.txt.

We can confirm.

$ cat animals.txt
dog
horse
cow
chipmunk
foobar

As you can see foobar is appended. Success!

We can close file descriptor 4 now.

$ exec 4>&-

Nice!

More from this blog

Linux and Web

31 posts