Search code examples
bashfindshhardlink

bash if then cp as hardlinks


I would like for the following to hardlink all files to destination, except those directories defined. The find piece is working, but it won't copy any files.

#!/bin/sh
tag_select=$1
source=$3
dest="/backup/"

{
if [[ "$1" = "backup" ]]; then
    find . -mindepth 1 -maxdepth 1 ! -name "dir1" ! -name "dir2" | while read line
    do
        cp -lr "$3" "$dest"
    done
fi
}

Please note, I do not want to use rysnc as I would like to create hardlinks in the destination. Thank you in advance!


Solution

  • I guess you know why "$2" doesn't appear anywhere, so we will just presume you are correct. You also understand that every file you find source (e.g. "$3") will be linked to $dest no matter what filenames are discovered by find because you make no use of "$line" that you use as your while read line loop variable. It appears from the question, you want to link all files in source in dest (you must confirm this is your intent) If so, find itself is all you need, e.g.

    find source -maxdepth 1 ! -name "dir1" ! -name "dir2" -execdir cp -lr '{}' "$dest" \;
    

    which will find all files (and directories) for 1-level and hardlink each of the files in dest. If that wasn't your intent, please let me know and I'm happy to help further. Your original posts was somewhat an opaque pot of shell stew...