Echo vs Cat

Hello!

I have been searching the internet but have yet to come across a concise, straightforward explanation of what the difference between the commands ‘echo’ and ‘cat’ is.
Could anyone please define the difference and also why you might to choose one over the other for a given use?

Thanks in advance!

Hi @taylorrayne !

So I guess you are talking about the command line. Echo simply displays its arguments on the standard output. If no arguments are given, Echo outputs a blank line.
For example :

$ echo "Hello world"

The output will be :

Hello world

You can also use echo to to redirect the standard output of the command on the left and append it to the end of the file on the right.

For example :

$ echo "Hello world"  >> hello.txt

The output will be added to the file hello.txt.

Whereas the command cat displays the contents of one or more files to the terminal.
Example :

$ cat hello.txt

The output will be whatever text is in the hello.txt file, which is for instance :

Hello world

Hope that helps. There is also the course Learn command line where you can learn more and get some practice if you haven’t done it yet.

Happy coding !

1 Like

Hey @chrisgeek07. Thank you for this explanation!
So, from what I understand, echo simply echoes/parrots (:parrot:) its input, whereas cat actually performs more of an in-depth function - that is, given a file name it doesn’t just return the file name as echo would but reads the file instead.
For instance,

$ echo file_1.txt > file_2.txt
$ cat file_2.txt
>>> file_1.txt

however

$ cat file_1.txt > file_2.txt
$ cat file_2.txt
>>> 'text from file_1.txt' 

Would this be correct? If so, what is the real functionality of echo?.. it seems somewhat redundant, unless maybe in the case of pipping.

2 Likes

You got some pretty good points right here. Well the functionality of echo again depends on the context and environment that its being used. Yes indeed, one good use of echo in piping and also redirecting output. You just have to see what works best for what you want to do with these commands.

1 Like

I’ve always though of echo as closer to something like Python’s print, one of the simplest uses is querying variables, e.g. echo $var1. It might have more uses but for the fact that most commands direct to stdout anyway. If you look up printf vs. echo e.g. on stackoverflow you’ll find a lot of discussion about viable alternatives.

The only other use I can find from searching is to directly display the output of tricks like globbing, e.g. echo ab* without expanding directories like ls defaults to.

It is nice and simple, perhaps there are more uses but you may never need them and other tools might be better to work with.

2 Likes

Thank you both for your insight :slight_smile: , @chrisgeek07 @tgrtim

2 Likes