Search code examples
linuxbashpiping

How do I make a bash function to create multiple named directories and then organize their included files by extension?


I'm trying to create a bash function script that will allow me to create multiple directories with the names below. Every time I run it i does both echos fine but in between it says (mkdir: ./: File exists), but the are no files there already. What am I doing wrong? I should add that the script is another folder in my root directory named bin just to be clear.

   #!/bin/bash

    echo "Creating directory categories"

    function make_folder 
    {
        cd -; cd content; sudo mkdir ./$1
    }

    make_folder "documents"
    make_folder "other"
    make_folder "pictures"
    make_folder "media"

    echo "Directories have been made"; cd -
    exit

Update: I'm also trying to organize files by extension into their corresponding folders (i.e. .jpg into pictures, .doc into documents, .gif into media, etc).

   ext="${filename##*.}" #set var ext to extension of files

   find ./random -name | #find and list all files in random folder
                         #pipe results of find into if statement

   if ext == ["jpg"; "jpeg"; "png"] #move ".jpg", etc to new destination
        then
          mv /path/to/source /path/to/destination

   elif ext == [".gif"; ".mov"] #move ".gif", etc to new destination 
        then
          mv /path/to/source /path/to/destination
   else                         #move other files into to new destination
          mv /path/to/source /path/to/destination
   fi

Solution

  • In bash, arguments to functions are accessed via variables $1, $2, etc.

    As written in the question the variable $folder hasn't been set and so the mkdir ./$folder command will expand to be mkdir ./, which exists (hence the error message)

    The following minor tweak would help:

    
    function make_folder 
        {
            folder=$1
            cd -; cd content; sudo mkdir ./$folder
        }