0

I am in need of a bash script to recursively watch a folder and symlink every new file and subdirectory to another folder.

this script correctly symlinks subdirectories and their contents:

#!/bin/bash

inotifywait -r -m '/source_dir' -e create -e moved_to |
    while read dir action file; do
 cp -as $dir/$file /destination_dir/$file
done

However, the problem is that if a file gets added to a sub directory, a symlink will be created directly in the destination directory instead of its respective subdirectory , how do I rectify this?

1 Answer 1

1

You need to use the directory path in the target destination

#!/bin/bash
#
src='/source_dir'
dst='/destination_dir'

inotifywait -r -m "$src" --format '%w%f' -e CREATE,MOVED_TO |
    while IFS= read -r item
    do
        # echo "Got $item"
        if [[ ! -d "$item" ]]
        then
            echo mkdir -p "${item%/*}"
            echo cp -as "$item" "$dst/${item#$src/}"
        fi
    done

Remove the two echo prefixes when you're happy it's doing what you expect. Uncomment the echo "Got $item" to see some of what's going on.

Please note that it is not possible to use inotifywait in this manner to handle file or directory names that contain newlines (adding \000 or even \001 to the --format string, with or without $'...' seems to prevent inotifywait from delivering any status updates at all).

9
  • I get cannot stat "/filename" as if I didn't specify the full path to the file when trying to use this.
    – user5672
    Nov 9, 2020 at 23:12
  • There's no filename in my example. Since your original had paths modified, and I've used those here, please convert your failure message back to something that matches here too Nov 9, 2020 at 23:13
  • I am not sure if I am understanding you correctly or if am not explaining myself well, I literally just get "cp: cannot stat '/file_that_should've_been_symlinked' " as an error message.
    – user5672
    Nov 9, 2020 at 23:17
  • You can't have done unless you've already removed the echo statements. In which case, put them back until you're happy it's doing what you expect Nov 9, 2020 at 23:19
  • I did remove them. This is what echo prints out: mkdir -p /destination_dir cp -as /filename /destination_dir/filename
    – user5672
    Nov 9, 2020 at 23:31

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .