3

The operation I'm trying to do is take directory 1:

Dir1
    Dir A
        File A
    Dir B
        File B

Then use the find command to check every file in Dir 1 for whether or not they have an existing hardlink with something like:

find . -type f -links 1 -exec cp -al {} /path/to/Dir2/{} \;

Then I want to end up with:

Dir2
    Dir A
        File A (hardlink)
    Dir B
        File B (hardlink)

Right now I know how to find every non-hardlinked file in a directory, and place a hardlink to those files in a different directory, but I want to maintain the same directory structure when I make the new hardlinks. My current command would produce this:

Dir2
    File A (hardlink)
    File B (hardlink)

Say I'm looking at File B, and File B has only 1 link (has not been hardlinked), how would I refer to "Dir B" in order to copy that directory to the new directory? I wouldn't want "/Path/To/Dir B" just "Dir B".

Is there a way to accomplish this task in bash?

2 Answers 2

0

You could do that with tools like find, and mkdir

In a bash file .sh dont forget to replace /path/to/Dir1 with the source directory path and /path/to/Dir2 with the destination directory path.

#!/bin/bash

src_dir="/path/to/Dir1"
dest_dir="/path/to/Dir2"

find "$src_dir" -type d -print0 | while IFS= read -r -d '' dir; do
    dest_subdir="${dir/$src_dir/$dest_dir}"
    
    mkdir -p "$dest_subdir"
    
    find "$dir" -maxdepth 1 -type f -links 1 -print0 | while IFS= read -r -d '' file; do
        cp -al "$file" "$dest_subdir"
    done
done
0

Yes, you can accomplish this task in bash by using the rsync command instead of cp and modifying your find command to use variables. Here is an example command that should work for your needs:

#!/bin/bash
# Set source and destination directories
src_dir="Dir1"
dest_dir="Dir2"

# Use find to locate all files in source directory with only one link
find "$src_dir" -type f -links 1 | while read file; do
  # Get the directory name of the file and create the corresponding directory in the destination
  dir=$(dirname "$file")
  mkdir -p "$dest_dir/$dir"

  # Copy the file using rsync with the -l (hardlink) option
  rsync -av --link-dest="$src_dir" "$file" "$dest_dir/$file"
done

You must log in to answer this question.

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