3

I'm attempting to move all the files in a series of directories into a subdirectory of their respective folder. There are many folders that need to have this happen to, so I've put it in a loop. For the sake of the example, I've reduced the number.

read var1
case ${var1} in a) sub="sub_directory1";; b) sub="sub_directory2";; esac

for ((i=1; i<=5; i++)); do
   case ${i} in
     1) t=a;; 2) t=b;; 3) t=c;; 4) t=d;; 5) t=d;;
   esac
   mv "${location[files]}${t}/*.*" "${location[files]${t}/${sub}
done

${location[files]}, ${t}, and ${sub} are all directories so that the structure looks similar to this:

/files/a/file1.txt
/files/a/file2.txt
/files/a/sub_directory1
/files/a/sub_directory2
/files/b/file33.txt.3824
/files/b/file52f.log.345
/files/b/sub_directory1
/files/b/sub_directory2

so on and so forth. The idea is that files in /files/a/ will be moved to files/a/sub_directory1.

When I run this in the script, it appears to expand the variables properly, but evidently not the correct way for mv. I get

mv: cannot rename files/a/*.* /files/a/sub_directory1/*.*:
No such file or direbctory

When I do that same command manually:

mv /files/a/*.* /files/a/sub_directory1

it works as intended.

Is it that the wildcards are being treated literally?

Jahid
  • 21,542
  • 10
  • 90
  • 108
mkingsbu
  • 354
  • 3
  • 20
  • 3
    Inside double quotes globs do not expand. You need to leave them out of the quotes. – Etan Reisner Jul 15 '15 at 18:50
  • For anybody else new to bash like myself in the future who may read that, Etan's comment solved my problem. I moved the quote to before the asterisk in the MV command. – mkingsbu Jul 15 '15 at 18:57
  • What is the motivation behind this script? – chicks Jul 15 '15 at 19:36
  • 1
    @chicks - I load files at my job that all have to go in a series of specific folders that have identical file structures. But I have to ensure that every folder that I load from has only the two subdirectories in it or else files get duplicated. I always load them into the same subdirectory (*/sub_directory1). That's what this specific part of the script handles. The other parts prep all of the file extensions to go into their correct respective folders, copy the new files, and then populate the fields where they're supposed to go. – mkingsbu Jul 15 '15 at 20:05
  • 1
    @mkingsbu : you can post your corrected code as an answer and then accept it after 48 hrs to give yourself more reputation points. Good luck to all. – shellter Jul 15 '15 at 23:46

1 Answers1

2

Double quote prevents word splitting and globbing while allowing variable expansion, i.e "*.*" is just a string literally *.*. To do globbing on filenames, you can do:

mv "${location[files]}${t}"/*.* "${location[files]}${t}/${sub}"

More info on Bash manual.

Jahid
  • 21,542
  • 10
  • 90
  • 108