params_noob params_noob - 2 months ago 6
Bash Question

Copy contents of multiple directories inside current directory into new directory

Brand new to

.sh
and I'm trying to backup images from an old iPhone where images were placed into a new directory for date. There are hundreds of directories where I need to take the pictures from each and dump them all into one directory.

My best attempt:

#!/bin/bash
function process () {

a=1
for i in *
do
cp -r i ${dir}
let a=a+1
done

}

#Interview
echo "This script will take the contents of each directory in the current directory and move it's contents into a new directory that you will specify"
echo "Name your new directory"
read dir

#Confirm
read -p "Your new directory will be ${dir}. Continue?" -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]
then
process
fi


Errors recieved:

massmove.sh: line 1: $'\r': command not found
massmove.sh: line 2: $'\r': command not found
massmove.sh: line 3: $'\r': command not found
massmove.sh: line 4: syntax error near unexpected token `$'{\r''
'assmove.sh: line 4: `function process () {


Update: Improved via deefff's answer:

function process () {

for i in */*.*
do
cp -r $i ${dir}

done

}

echo "This script will take the contents of each directory in the current directory and mv it's contents into a new directory that you will specify"
echo "Name your new directory"
read dir
mkdir ${dir}

echo process


Still is throwing these errors:

massmove.sh: line 2: syntax error near unexpected token `$'{\r''
'assmove.sh: line 2: `function process () {


Could this be a WSL bug?

I understand that

cp */*.* ${dir}


is a quick and powerful way to accomplish my task but i'm also very interested in what is causing the errors.

Answer

* will match every entry, including directories, so in its current form, it will copy the whole directory structure, which I guess, is not what you want. Also, you should refer to the variable i as $i in the cp command. Also, the a variable seems pointless. Try it like this:

function process () {

for i in */*.*
do
  cp $i ${dir}
done

}

In fact, I just realized that this should do the trick as well:

cp */*.* ${dir}