0

I want to loop recursively through every file and directory below an specified path and echo that file/directory's owner and name.

I found this question to be a good reference, but I would like to know if there is a bash 3.2 portable and simpler solution to the problem. A solution without using find would be excellent.

I also discovered there is shopt -s globstar, but I don't know whether it is portable or not.

If you look at my script, you will see that log_owners simply loops over $@, so maybe the problem is in my glob pattern. I thought log_owners $root/** would loop through everything, but it didn't.

# OSX check.
darwin() {
  [ $(uname) = "Darwin" ]
}

# Get file/directory's owner.
owner() {
  if [ -n "$1" ]; then
    if darwin; then
      stat -f "%Su" "$1"
    else
      stat -c "%U" "$1"
    fi
  fi
}

log_owners() {
  for file in $@; do
    echo $(owner "$file")"\t$file"
  done
}

I am using sh/bash 3.2.

Community
  • 1
  • 1
Jorge Bucaran
  • 5,588
  • 2
  • 30
  • 48

1 Answers1

0

Well, I just realized the rather obvious (using recursion):

loop() {
  for file in $1/**; do >/dev/null
    if [ -d "$file" ]; then
      loop "$file"
    elif [ -e "$file" ]; then
      echo $(owner "$file")"\t$file"
    fi
  done
}

And it seems to be working alright.

Jorge Bucaran
  • 5,588
  • 2
  • 30
  • 48
  • try running `time find /base/dir -ls` vs `time loop /base/dir` or a reasonably large dir structure. The hh:mm:ss info at the end will help you decide if this is a good approach or not. Also, you didn't define portable. Portable as in POSIX compatible, or as /bin/sh compatible, or as you seem to be saying portable='oldest possible version of bash'. ;-) Good luck! – shellter Mar 09 '15 at 10:54
  • I see, I think I meant `/bin/sh` compatible. I think the recursive functions although simple is really slow. – Jorge Bucaran Mar 09 '15 at 13:32
  • As it stands, it is not /bin/sh compatible. The `$( )` syntax, the globstar syntax, the 'owner' command are not /bin/sh. What operating systems/machines will this be running on? – Brad Lanam Mar 09 '15 at 15:19
  • Thanks! @BradLanam Mac and Linux flavors. – Jorge Bucaran Mar 09 '15 at 15:21
  • Well, I think you are probably just fine w/the bash script you have then. Having it bash-compatible should be ok. – Brad Lanam Mar 09 '15 at 15:23