Knowledge Base

Preserving for the future: Shell scripts, AoC, and more

Shell functions for testing other functions

When I am updating or adding to my scripts package, I like to find out the fastest way to execute a task. This involves using the time command and a few wrapper functions. Here's an example. I was updating my lsd (list directories) function, and I wanted to see how fast it is compared to a variant I was considering.

func() { pushd "${1}" 1>/dev/null 2>&1 ; find $( find . -maxdepth 1 -type d -printf '%p\n' | sed -r -e 's/^\.\/?//;' | sed -r -e '/^\s*$/d' ) -maxdepth 0 -exec ls -ldF --color=always {} + ; popd 1>/dev/null 2>&1 ;  } ;

func_wrapper() { __x=0 ; while test ${__x} -lt ${1} ; do __x=$(( __x + 1 )) ; __func "${2}" "{$3}" ; done ; }

So now you can run the wrapper and tell it how many times to loop:

time func_wrapper 1000 . 1>/dev/null

real    0m6.081s
user    0m2.103s
sys     0m5.157s

Comments