Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Bash Script File Copy

Tags:

bash

I am having trouble with a simple grading script I am writing. I have a directory called HW5 containing a folder for each student in the class. From my current directory, which contains the HW5 folder, I would like to copy all files starting with the word mondial, to each of the students' folders. My script runs but does not copy any of the files over. Any suggestions?

#!/bin/bash                                                                                                         

for file in ./HW5; do
    if [ -d $file ]; then
        cp ./mondial.* ./$file;
    fi
done

Thanks,

like image 773
lbrendanl Avatar asked Jul 22 '26 02:07

lbrendanl


1 Answers

The first loop was executing only once, with file equal ./HW5. Add the star to actually select the files or directories inside it.

#!/bin/bash                                                                                                         

for file in ./HW5/*; do
  if [ -d "$file" ]; then
    cp ./mondial.* ./"$file"
  fi
done

As suggested by Mark Reed, this can be simplified:

for file in ./HW5/*/; do 
  cp ./mondial.* ./"$file"
done
like image 105
piokuc Avatar answered Jul 23 '26 16:07

piokuc