linuxbashfunctiondotfilesunix-head

Bash function argument unexpectedly interpreted as file/directory


I created a function in my .bashrc file to print the top N files/directories in the working directory:

# .bashrc
function topN () { du -hs * | sort -rh | head -"$1"; }

However, sourcing my .bashrc and then running topN 5 returns:

head: cannot open '5' for reading: No such file or directory

I have attempted various quoting methods and combinations, with generally the same error. How can I re-write this function to treat the argument 5 as a value rather than a file/directory?

Simply running du -hs * | sort -rh | head -5 returns the expected listing of the top 5 files/directories and their sizes.


Solution

  • You were running a (stale) alias rather than the function you shared with us.