I'd like to sort all the directories/files in a specific directory based on their size (using du -sh "name").
I need to apply this command to all directories in my location, then sort them based on this result. How can I do that ?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
With GNU sort and GNU du (which it appears you have, since you state you are using
du -sh -- * | sort -rh # Files and directories, or du -sh -- */ | sort -rh # Directories only
The output looks something like this:
22G foo/ 21G bar/ 5.4G baz/ 2.1G qux/ 1021M wibble/ 4.0K wobble/
This is an improved version based on jabalv's answer. It works with a GNU as well as a BSD userland.
IFS='\n' du -sk -- * | sort -n | cut -f2 | while read line ; do xargs du -sh "$line" done
4.0K games 2.7M local 6.7M lib32 19M sbin 152M src 177M include 321M bin 2.2G share 2.9G lib
To reverse the sort order and list the largest files and directories first, use