0

The many related questions got me to a command the works as I want. Running this on the CLI shows the non-hidden (not starting with '.') directories and does not descend into them.

find /home/pbw10 -type d -path '*/.*' -prune -o -not -name '.*' -print

But if it's in a function, all of the directories are shown, as well as the files. The example is simplified from what I'm actually doing to make it clearer where the issue is.

runIt() {
    thePath='/home/pbw10'
    theCmd="find $thePath -type d"
    theCmd+=" -path '*/.*' -prune -o -not -name '.*' -print"
    # Show it.
    echo "$theCmd"
    # Runs it.
    # This does not exclude the hidden directories (or files).
    echo "$($theCmd)"
}

I rarely use bash functions, so I'm hoping this is something simple and obvious to those are more familiar with it.

  • 1
  • The two above references contain everything you need. The first contains a valid solution based on shell arrays (non POSIX, therefore non portable, although possible in bash). The second by ilkkachu not only covers arrays but also, for portability, how operands contained in the pseudo array "$@" and the use of eval can be a solution. Both explain what and how you need to quote. – Cbhihe Sep 20 '21 at 19:49
  • 1
    Note that this has nothing to do with functions, but with storing the command in a variable. Also, echo "$(somecmd)" is a bit redundant, you could just directly run somecmd. (it only makes a difference if somecmd produces output that ends in 0, 2, or more than 2 newlines.) – ilkkachu Sep 20 '21 at 20:53
  • Thanks to all above, it was enough to get it mostly working. I should have stuck with Python. :-)

    I'm using arrays because I don't need portability. Is it possible to parenthesize sections using arrays? I can fix it by adding a second "-type d" section if not.

    – OPunWide Sep 20 '21 at 21:05
  • @OPunWide, basically you assign the args to the array just as you'd use them on the command line. So, e.g. find . \( -name '*.foo' -o -name '*.bar' \) -print -> args=(find . \( -name '*.foo' -o -name '*.bar' \) -print); "${args[@]}" – ilkkachu Sep 20 '21 at 21:31
  • I don't have enough points in this part of the site to upvote anything. What fixed the problem for me was the information on using an array. Sometimes it's amazing how much stuff you can fumble through without knowing something basic like that. If one of you wants to make using the array into an answer I'll accept it, or this question can die a natural death. Thanks either way. – OPunWide Sep 21 '21 at 20:48

0 Answers0