Hi, I have finished the Command Line course and still have a couple of questions

What`s the difference between

cat filename.txt | sort and sort filename.txt?
It results in the same output, doesn’t it? Why do we need to use a “|” in this case? Can anyone give an example, of when using “|” in a similar case would be more efficient?

cat < filename.txt
Is it the same with
cat filename.txt?
Why do we need the “<” then? Can anyone give a better example of using “<”?

cat file1.txt | wc | cat > file2.txt
Why do we need “cat” before redirecting the stdout of “wc” command to file2.txt?

A lot of these things may seem redundant but they are to familiarize yourself with different tools in the command line.

I’ll start with number 2. When you issue the command cat filename.txt what’s essentially happening is you’re telling the computer you want to execute the program cat with the arguments filename.txt. The important thing to note here is that the cat program specifically accepts arguments like this (read more in man cat).

What’s the difference with using the < redirection operator then? Well, here nothing. But under the hood < actually places the redirected file in a buffer. Imagine you have an executable file myProgram that doesn’t execute with arguments but does take in input at some point.

This program can be something that prompts the user like this

Please enter your name:
Please enter your age:
Please enter your city:

You can run it by hand and input manually, or you can redirect a txt file of your answers myProgram < myAnswers.txt and have it process your answers. This would be useful with large files of scientific data for example. (Granted, depending on how you write your program, it can take file names as argument by default, but this is not always the easiest or fastest option depending on what language you’re writing in).

For the rest of the other questions it’s a very similar idea. cat, sort, and wc are specific programs. The pipe is a way for programs (processes) to communicate with each other in the command line, and sometimes you will have programs that don’t necessarily have automatic capabilities like these, so you’ll need to compose very specific expressions to get what you need.

1 Like