Search code examples
bashshellglobqnx

How to recursively search directories in a minimal shell (no grep, find, etc.)?


I'm working with an embedded system running QNX that has a stripped-down shell (KSH).

I want to locate all run all executables on the filesystem that match the following:

*/shle/*-*_test

The "shle" directory may appear up to 4 levels deep under root. My current approach is to run the following commands:

for shle in ./shle ./*/shle ./*/*/shle ./*/*/*/shle
do
  for exe in $shle/*-*_test
  do
    echo running: $exe
    $exe
  done
done

Is there a cleaner or faster way of doing this? Are there commands other than grep and find that I should try?


Solution

  • If you don't have find, you can't do much better than what you did: enumerate the levels. If you needed to go down to arbitrary levels, you could do it with a recursive function (but watch out, recursion is tricky when all you have is global variables). Fortunately, with a known maximum depth, it's a lot simpler.

    There's a little room for improvement: you'd better put double quotes around all variable substitutions, in case there's a filename somewhere that contains whitespace or special characters. And you aren't testing whether $exe is exists and executable (it could be the pattern …/*-*_test if that pattern doesn't match anything, or perhaps it could be a non-executable file).

    for shle in shle */shle */*/shle */*/*/shle; do
      for exe in "$shle"/*-*_test; do
        test -x "$exe" && "$exe"
      done
    done
    

    If you don't even have test (if you have ksh, it's built-in, but if it's a stripped-down shell it might be missing), you might get away with a more complicated test to see if the pattern was expanded:

    for shle in shle */shle */*/shle */*/*/shle; do
      for exe in "$shle"/*-*_test; do
        case "$exe" in
          */"*-*_test") :;;
          *) "$exe";;
        esac
      done
    done
    

    (I'm suprised that you don't have find, I thought QNX came with a full POSIX suite, but I'm unfamiliar with the QNX ecosystem, this could be a stripped-down version of the OS for a small device.)