When doing automated processing, don't make your life more complicated by using numbers in different units. Don't pass -h
to du
. Then you can use simple numerical sorting on the output, and your script will still work if you have more than 1 TB in one of the directories.
du -s ~/* | sort -k 1n | tail -n1
This always prints out a line, even if the largest subdirectory contains less than 1 GB. If that's not what you want, you can replace the conditional “is the output empty” by “is the number less than the threshold”.
To extract the directory name, take the output and remove the part up to the first tab.
largest_directory=$(du -s ~/* | sort -k 1n | tail -n1)
largest_directory_size_kB=${largest_directory%%$(printf '\t')*} # if you need the size
largest_directory=${largest_directory#*$(printf '\t')}
awk
part withawk -v q="'" '{ print q$2q }'
du -sh $HOME/* | grep '[0-9]G\>' | sort -k 1rn | head -1 | awk '{ print $2 }'
Gives/Users/user/Big
awk -v q="'" '{ print q$2q }'
will give'/Users/user/Big'
but we are almost there...!cd "$VAR"
will