learner learner - 3 months ago 5
Bash Question

Unix command to get list of directories over remote host

I am trying to do ssh to a remote machine and get list of directory names present at pathA(/home/abc/mydata) which has any file that has been modified in last 1 hours.

Directory:-

/home/abc/mydata
-> Directory a
->file1 last modified 1 hour back
->file2 last modified 1 year back
->file3 last modified 1 day back
-> Directory b
->file11 last modified 1 year back
->file22 last modified 1 year back
->file33 last modified 1 year back
->Directory b1
->fileb1-11 last modified 1 hour back
-> Directory c
->file111 last modified 1 year back
->file222 last modified 1 year back
->file333 last modified 1 year back


I am trying to get output as

a => as it has 1 file which was modified 1 hour back(file1)
b => as it has 1 file under sub directory of directory b (fileb1-11)


I am trying the following command

ssh "host" -t "find /home/abc/mydata -type d -mmin -60 -ls"


however I want the final output as

a
b


but this command lists the sub directories also as the output.

a
b
b1


Some help will be great.

Answer

Try:

ssh "$host" '
find /home/abc/mydata -mindepth 1 -maxdepth 1 -type d |
while read -r d; do
    [ "$(find "$d" -mmin -1 -type f -print -quit 2>/dev/null)" ] &&
    ls -ldi "$d"
done
'

Notes:

  • With mindepth/maxdepth, the first find will look only at level 1.
  • A separate find will look inside each subfolder for regular files (-type f) recently modified. If other recently modified file types (subdirectories/sockets/symlinks) should trigger the output, remove -type f.
  • The -t parameter to ssh is only necessary if you want colorized ls output.
  • The output of ls -ldi ... is slightly different from that of find ... -ls, but I'm guessing it will do.
  • The return value of the second level find is too vague to use here. Instead, we simply test if its output is nonempty.
Comments