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:


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


New files created from /home/my_user/folder1 path


New files created from /home/my_user/file3 path


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:


#need to implement relative paths

#clears the old folder
rm -r ./system

#goes through all the arguments
for var in "$@"
    #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
        echo "$var ERROR"

When it is a folder i think it works fine:


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.


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.