Creating shortcut to list directories and files in ascending order

Este post também está disponível em: Português (Portuguese (Brazil))

The du command is present in all Linux distributions and is very useful for listing the size of files and directories.

If you want to list, for example, the size of all files and subdirectories of the current directory, just use the command below:

 du -sch ./*

Note that with the above command, the list will not be sorted by size. To list the command output in ascending order, let’s use the command block below and then create a simple shortcut.

du -sk ./* | sort -n | awk 'BEGIN{ pref[1]="K"; pref[2]="M"; pref[3]="G";} { total = total + $1; x = $1; y = 1; while( x > 1024 ) { x = (x + 1023)/1024; y++; } printf("%g%s\t%s\n",int(x*10)/10,pref[y],$2); } END { y = 1; while( total > 1024 ) { total = (total + 1023)/1024; y++; } printf("Total: %g%s\n",int(total*10)/10,pref[y]); }'

Memorizing the block above would be a difficult task, to solve this problem, let’s create a shortcut, which will execute the command block whenever we type a defined word.

Create the following file and paste the contents of the command block we created earlier

nano /usr/bin/tamanho

Change file permissions

chmod +x /usr/bin/tamanho

From now on, whenever you type the word size in any folder you are accessing, the size of folders and files will be listed, sorted from smallest to largest.

Need some assistance on your Server? We can help you!