Script Bash - Cp Target Is Not a Directory - Using Variables

Script Bash - Cp Target Is Not a Directory - Using Variables

I know that this type of questions maybe were duplicated. But in my case, I'm use a variable that contains the destination directory and the error says, that is not a valid directory.

cp target var2 is not a directory

Now, this is my code, I'm trying to copy all images from the folder images (contained in Desktop) to the folder photos (In desktop too and empty). I use GIT Bash for Windows 10

function pause(){

    read -p "$*"
}

echo "Help: Use the bar / to separate the directory names"
echo ""

echo "Enter the directory location"
read var1

echo "Enter the destinity directory location"
read var2

for var1 in "var2"
do
    cp * var1 var2
done

echo ""
pause "Press [ENTER] to continue..."

What's my mistake? Thanks!

When i execute the script, the directory I use is:

C:/Users/Mauri/Desktop/images

And the var2 is:

C:/Users/Mauri/Desktop/photos

With this code into the for:

cp -r * $var1 $var2

Was moved all archives in the desktop to photos folder, It's not my objetive, I want to move only the images contained on the image folder in the desktop to the empty folder photos in the desktop too.

2

1 Answer

Instead of your for loop, it would be great if we could run cp "$var1/"*.{jpg,png,gif} "$var2". That would be an easy way to copy all of the files with extension jpg, png, or gif from $var1 into $var2. Unfortunately, that command fails if there happen to be no files with one of the given extensions, for example if we have several jpg files but no gifs.

So we have to make things a little more complicated, and our answer is the find command, as shown below. If you want to add more image file types, just add another set of -o -name '*.EXT' within the parentheses, where EXT is the file extension you want.

function pause(){

    read -p "$*"
}

echo "Help: Use the bar / to separate the directory names"
echo ""

echo "Enter the source directory"
read source

echo "Enter the destination directory"
read dest

find $source \( -name '*.jpg' -o -name '*.gif' -o -name '*.jpeg' -o -name '*.png' \) -exec cp -prv {} $dest \;

echo ""
pause "Press [ENTER] to continue..."

The -prv flag on cp means preserve attributes, copy recursively, and use verbose mode (print what has been copied).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Elena Rostova
Author

Elena Rostova

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.