Sort in Bash Scripting

We recently just looked at grep in bash scripting, and another commonly used program in bash scripting is the program called sort.

Sort is a simple filter that is used to sort lines of text from its input, input can be your keyboard input, a file, or even an output of another program.

This is its syntax:

sort filename

You simply type sort followed by the name of the file name you wish to sort, or you can simply pipe the result from another program, e.g:

lastlog | sort

Common mistake to avoid when sorting:

When you sort an input and redirect it to another output, you might typically do something like this:

sort file1 > file1

So, in the above example, you basically want to sort the contents of file 1 and replace it with the sorted output. The issue with this command is that once you execute it, you will lose all the data in that file.

What actually happens under the rader is that before the sort program starts, the shell looks at the greater than symbol, and thinks you want to prepare the file for the output that the program is gonna store in it, so, if there is any existing file, it would erase it, and then call the program, but by the time the program runs, you are practically sorting an empty file.

The correct technique would be:

sort file1 > file2
mv file2 file1

So, you sort it, and send the result to another file. You can then rename file2 to file1. You might think this applies to only the sort program, which is not true, it applies to all filters in general, so, you should definitely be careful.

Comment policy: Respectful and beneficial comments are welcome with full open hands. However, all comments are manually moderated and those that doesn't relate with what the passage is saying or offensive comments would be deleted. Thanks for understanding!

Leave a Reply

Your email address will not be published. Required fields are marked *