How to Use Redirection to Create Files in Linux on Your Raspberry Pi
It’s possible to send the results from a command to a file instead of the screen on your Raspberry Pi; in other words, to redirect them. You could keep some listing results in a file, for example, so you have a permanent record of them or so you can analyze them using a text editor.
You turn screen output into a file by using a greater-than sign and the filename you’d like to send the output to, like this:
ls > listing.txt
You don’t need to have the file extension of .txt for it to work in Linux, but it’s a useful reminder for yourself, and it helps if you ever copy the file back to a Windows machine.
Try using this command twice from two different directories and then looking at the contents of listing.txt with the less command. You’ll see just how unforgiving Linux is. The first time you run the command, the file listing.txt is created. The second time you do it, it’s replaced without warning. Linux trusts you to know what you’re doing, so you need to be careful not to overwrite files.
If you want a bit of variety, you can use some other commands to display content on screen:
echo: This displays whatever you write after it on screen. You can use it to solve mathematics problems if you put them between two pairs of brackets and put a dollar sign in front, for example:
date: This shows the current time and date.
cal: This shows the current month’s calendar, with today highlighted. You can see the whole year’s calendar using the option –y.
If you want to add something to the end of an existing file, you use two greater-than signs, as you can see in this example:
pi@raspberrypi ~ $ echo I made this file on > testfile.txt pi@raspberrypi ~ $ date >> testfile.txt pi@raspberrypi ~ $ cal >> testfile.txt pi@raspberrypi ~ $ echo $((6+31+31+28+31+7)) Days until my birthday! >> testfile.txt pi@raspberrypi ~ $ less testfile.txt I made this file on Sat Nov 24 14:40:43 GMT 2012 November 2012 Su Mo Tu we Th Fr Sa 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 134 Days until my birthday!
You can use redirection like this to create some files you can practice copying and deleting. If you don’t want to spend time creating the file contents, you can make some empty files by redirecting nothing, like this: