0

This is my code, something in the rec_copy() function isn't working properly, the extension named folders are created in the destination folder but the files are not copied there.

#!/bin/bash
if [ $# -ne 2 ]
then
        echo "Usage: $0 <source> <destination>"
        exit
fi

if [ ! -d $1 ]
then
        echo "Source folder does not exist"
        exit
fi

if [ -d $2 ]
then
        rm -r $2
        mkdir $2
else
        mkdir $2
fi

extension=`ls -l $1 | grep -v "^d" | awk '{ print $10; }' | sed 's/^.*\.//g'`
for f in $extension
do
        if [ ! -d $1/$f ]
        then
                mkdir $2/$f
        fi
done

rec_copy(){
folder=`ls $1`
for f in $folder
do
        dest=`echo "$f" | sed 's/.*\.//g'`
        if [ -f $1/$f ]
        then
                cp $1/$f $HOME/$2/$dest
        elif [ -d $1/$f ]
        then
                rec_copy $1/$f
        fi
done
}

rec_copy $1
3
  • Sure $10 is the correct file name? What if file names contain spaces? Commented Aug 28, 2018 at 18:25
  • It's a recursive function of course I'm calling it inside, that is the point. The $10 is the 10th column in ls -l, which is the file name itself. I think that the "cp $1/$f $HOME/$2/$dest" command is not working like I want it to work. If you just test the program you will see what the problem is. Commented Aug 28, 2018 at 18:40
  • link It's 10 in my case, ignoring the situation when there is a space in the name. I'm positive that's not the problem. When I copy the files in the home directory it all works great. Commented Aug 29, 2018 at 0:23

1 Answer 1

0

Here is the answer in case someone ever needs it:

#!/bin/bash

if [ $# -ne 2 ]
then
        echo "Usage: $0 <izvor> <destinacija>"
        exit
fi

if [ ! -d "$1" ]
then
        echo "Izvorniot folder ne postoi"
        exit
fi

if [ -d "$2" ]
then
        rm -r "$2"
        mkdir "$2"
else
        mkdir "$2"
fi

extension=`ls -l "$1" | grep -v "^d" | awk '{ print $10; }' | sed 's/^.*\.//g'`
for f in $extension
do
        if [ ! -d "$1/$f" ]
        then
                mkdir "$2/$f"
        fi
done

rec_copy(){
folder=`ls "$1"`
for f in $folder
do
        dest=`echo "$f" | sed 's/.*\.//g'`
        to=`cp "$1/$f" "$2/$dest"`

        if [ -f "$1/$f" ]
        then
                echo "$to"
        elif [ -d "$1/$f" ]
        then
                rec_copy "$1/$f" "$2"
        fi
done
}

rec_copy "./$1" "./$2"

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.