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))

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. Commented Oct 31, 2019 at 18:13

1 Answer 1


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

for file in "$@"
   # apply command to "$file"
# 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! Commented Oct 31, 2019 at 17:30

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .