0

So I am trying to sort files with specific extensions into specific folder (ones that have been chosen by user by command line arguments)

Lets say $1 (.jpg) $2 (.docx) etc

The script is all working and fine, but I am trying to write a loop that sorts these files into their folders (just simply based on their extensions, so .jpg into jpg folder, so basically mv .$1 $1) How can I write the loop so it will always add +1 into the command line argument until there is no more command line argument (lets say there are 5) and when there is no more argument, simply moves the unassigned files into a selected folder for it?

Here what i was trying to do

function sorting {
count = 1
while [ $count -le 5 ]; do
mv .$count $count
count=$((count +1))
done 
} 

Then we I tried to call the function in the script I used sorting

  • Your script snippets have some basic syntax errors; for example, that mv command needs a wildcard, and at least some of the variable references should be double-quoted. Also, I always recommend mv -i or -n when doing bulk/automated moves, to avoid accidentally overwriting files in case of name conflicts. Something like: mv -i *.$1 "$1". Also, run your script through shellcheck.net; it's good at pointing out common mistakes. – Gordon Davisson Oct 31 '19 at 18:13
0

You don't need an index to the arguments... Just do

for file in "$@"
do
   # apply command to "$file"
done
# work here on remaining files in directory

The $file variable will take the successive values of your input arguments. Note the "$@" syntax, this insures that if arguments (file names) contain spaces they will still be processed as one unit.

  • I can’t try it just now, left the lab for today, I will try it tomorrow morning, thanks for the answer! – Viktor Surányi Oct 31 '19 at 17:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.