Basic Output Redirection
In Linux, commands typically display their output on the screen. However, using I/O redirection, you can send this output to files instead. The most basic redirection operator is >
, which sends output to a file.
Let's start by creating a directory structure for our practice:
cd ~/project
mkdir -p io_practice
cd io_practice
Now, let's see how redirection works. When you use the echo
command, it displays text on the screen:
echo "Hello, Linux World!"
You should see this output:
Hello, Linux World!
To redirect this output to a file instead of displaying it on the screen, use the >
operator:
echo "Hello, Linux World!" > greeting.txt
This command doesn't produce any visible output because the text has been redirected to the file. Let's verify the file was created and contains our text:
ls -l greeting.txt
cat greeting.txt
You should see something like:
-rw-r--r-- 1 labex labex 19 Oct 25 10:00 greeting.txt
Hello, Linux World!
The >
operator creates a new file if it doesn't exist, or completely overwrites the file if it already exists. Let's demonstrate this by overwriting our file:
echo "New content replaces old content completely." > greeting.txt
cat greeting.txt
Output:
New content replaces old content completely.
As you can see, the original content is gone, replaced by the new content.