Your code is needlessly complicated. I believe that the issue is that you fail to call mv
if the destination directory doesn't already exist. You also seem to try to move thing to a directory in the root directory.
Consider
#!/bin/sh
for suffix do
mkdir -p -- "$suffix" || exit 1
mv -- *."$suffix" "$suffix"
done
or,
#!/bin/bash
suffixes=( "$@" )
for suffix in "${suffixes[@]}"; do
mkdir -p -- "$suffix" || exit 1
mv -- *."$suffix" "$suffix"
done
(Change the exit 1
to continue
if you want to skip forward to the next given suffix when a directory can't be created, rather than to terminate the script).
This would loop over all filename suffixes (not really file types as a file type in Unix are things like "regular file", "directory", "symbolic link" etc.), would create a subdirectory in the current directory named after that suffix, and then move all files with names ending in ."$suffix"
to that directory.
The command mkdir -p dirname
would not fail if the directory dirname
already exists.
Example run:
$ tree
.
|-- file1.mp3
|-- file1.png
|-- file1.txt
|-- file2.mp3
|-- file2.png
|-- file2.txt
|-- file3.mp3
|-- file3.png
|-- file3.txt
|-- file4.mp3
|-- file4.png
|-- file4.txt
|-- file5.mp3
|-- file5.png
|-- file5.txt
`-- script.sh
0 directory, 16 files
$ ./script.sh txt mp3
$ tree
.
|-- file1.png
|-- file2.png
|-- file3.png
|-- file4.png
|-- file5.png
|-- mp3
| |-- file1.mp3
| |-- file2.mp3
| |-- file3.mp3
| |-- file4.mp3
| `-- file5.mp3
|-- script.sh
`-- txt
|-- file1.txt
|-- file2.txt
|-- file3.txt
|-- file4.txt
`-- file5.txt
2 directories, 16 files
This should move all mp3 files in the current working directory into a folder named "mp3" and copy all mp3 files into that
.... please edit your postmyarray=("$@"); path="${myarray[0]}"
, dopath="$1"; shift; myarray=("$@")
. Then you wouldn't have to loop from the 2nd element to the last -shift
removes the 1st parameter from $@, so it never gets in tomyarray
. Also, you don't need myarray at all, you could just loop over $@.