1

I was traying to make a simple script that takes a file or folder path and copies it, preserving the full path, in a folder called system next to the script.

Exaple: Imagine I just have this folders in my system:

/home/my_user/copy_script
/home/my_user/folder1/file1
/home/my_user/folder1/file2
/home/my_user/file3

If I pass as arguments the paths /home/my_user/folder1 and /home/my_user/file3 I want to get this folder structure as output:

Files before runing the script

/home/my_user/copy_script
/home/my_user/folder1/file1
/home/my_user/folder1/file2
/home/my_user/file3

New files created from /home/my_user/folder1 path

/home/my_user/system/home/my_user/folder1/file1
/home/my_user/system/home/my_user/folder1/file2

New files created from /home/my_user/file3 path

/home/my_user/system/home/my_user/file3

The idea to have a copy of the config files in a folder that will be sync with gitlab preserving the same structure as my system.

My script till now looks like this:

#!/bin/bash

#need to implement relative paths
#https://stackoverflow.com/questions/3963716/how-to-manually-expand-a- 
special-variable-ex-tilde-in-bash/29310477#29310477

#clears the old folder
rm -r ./system

#goes through all the arguments
for var in "$@"
do
    #It is a folder
    if [[ -d $var ]]; then
        mkdir -p "$PWD/system/$var"
        cp -R $var "$PWD/system/$var/.."
        echo "$var FOLDER"
    #It is a file
    elif [[ -f $var ]]; then
        mkdir -p "$PWD/system/$var"
        cp -R $var "$PWD/system/$var/.."
        echo "$var FILE"
    #The path is not ok
    else
        echo "$var ERROR"
    fi
done

When it is a folder i think it works fine:

Example:

With the same folder structure as the beggining when we call copy_script /home/my_user/folder1

First creates the /home/my_user/system/home/my_user/folder1 path

Then copies folder1 in /home/my_user/system/home/my_user/

But with files this does not work because it creates folders that I do not need and the I can't copy the files.

Example:

calling copy_script /home/my_user/file3 will create /home/my_user/system/home/my_user/file3 path but then I can't create the file because there is a folder with the same name.

Could someone kindly explain me how to do this? Thanks.

  • 1
    Have you tried rsync -r . target_folder/? – l0b0 Aug 27 '18 at 9:58
  • I did not know the existence of that tool, thanks, that's the answer I was looking for. – edoelas Aug 27 '18 at 10:14

Your Answer

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

Browse other questions tagged or ask your own question.