0

I am trying to run this command

for c in ax
do
mkdir $TgtDir$c/$Date
cd $TgtDir$c/$DirNew
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
echo $DIR
echo find . -iname $tgt -exec cp --parents {} ../$Date \;
find . -iname $tgt -exec cp --parents {} ../$Date \;
done

it prints

/home/ax/new
find . -iname '*20170829*' -exec cp --parents {} ../20170829 ;

but doesnt copy anything. If I run the command that is echoed here (after adding the \ at the end, seems like echo is swallowing that as an escape) from the new directory, it works fine - and the files get copied into /home/ax/20170829/....

Any ideas what I am missing here?

1

I guess you're not really in the directory DIR; you execute cd in a subshell, but the working directory for the remaining commands stays at $TgtDir$c/$DirNew. You can verify this by calling pwd after echo $DIR.

Solution: Call cd directly, don't use a subshell or assign the result to a variable. Add the absolute target path to the copy command.

for c in ax
do
    mkdir $TgtDir$c/$Date

    DIR=$( dirname "${BASH_SOURCE[0]}" )
    cd "${DIR}"
    pwd

    find . -iname $tgt -exec cp --parents {} $TgtDir$c/$Date \;
done

Alternative: Use the source directory instead of "." in the find command.

for c in ax
do
    mkdir $TgtDir$c/$Date
    cd $TgtDir$c/$DirNew

    DIR=$( dirname "${BASH_SOURCE[0]}" )
    find "${DIR}" -iname $tgt -exec cp --parents {} ../$Date \;
done

Note: The code is not tested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.