Copying Multiple Files into a Subdirectory

Hello,

I'm very new to scripting languages and I'm to use shell script to write a utility to backup files with a specific extension into a subdirectory.

Here is what I have done.

#!/bin/bash

read -p "Enter file(s) extension: " FILE

if [ -e *.$FILE ]; then
         mkdir `whoami`.$FILE #To create a directory with the name of the current user and the extension of the file
         cp *.$FILE `whoami`.$FILE #Gives me error when I have multiple files of same type in my directory
elif [ -d `whoami`.$FILE ]; then
         echo "The directory already exits." #It should check to see whenever there is an existing directory or not but instead it gives me an error ": binary operator expected"
elif [ ! -e *.$FILE ]; then
         echo "Extension does not match"
fi

Any help is highly appreciated.

Thank you

#!/bin/bash

USER=$( whoami )
read -p "Extension : " EXT
DIR=${USER}${EXT}

log()
{
        errno=${1}; msg=${2}
        if [ ${errno} -eq 999 ]; then
                echo "INFO : ${msg}"
        elif [ ${errno} -ne 0 ]; then
                echo -e "ERROR : ${msg}\nExiting..."
                exit 1  
        fi
}

ls *.${EXT} >/dev/null 2>&1
log ${?} "No valid files with extension : ${EXT}"
        
if [ ! -d ${DIR} ];then
        log 999 "Creating ${DIR}..."
        mkdir -p ${DIR} >/dev/null 2>&1
        log ${?} "Could not create ${DIR}!"
else
        log 999 "${DIR} already exists..."
fi

log 999 "Copying *.${EXT} to ${DIR}..."
cp -f *.${EXT} ${DIR} >/dev/null 2>&1
log ${?} "Copy failed!"

HTH
--ahamed

1 Like

@alphanoob: There's a hanging double quote in the last elif condition. [ ! -e *.$FILE"] . This will throw an error.

Apart from this, the script will display a message cp: omitting directory `user.dat' when it tries to copy folder `whoami`.$FILE to itself.

By the way, what exactly is your question?

Hello,

Thank you very much for both of your replies. Apart from what has been noted in codes done by ahmad101. My question is to exactly copy the files of same types (e.g. txt, jpg) to another location.

Thank you

That is what is done, right?... EXT will have the extension and that will used to copy the files with that extension. Did I get it wrong?

--ahamed

1 Like

Thank you very much for your prompt response. Just one more question? If I want it able to get the extension as an argument what should I do exactly?

Get rid of the 'read' and use a positional variable like $1, $2, ...

Be sure to validate the arguments as given.

if [ "$#" -lt 1 ]
then
        echo "Not enough arguments"
        exit 1
fi

EXT="$1"
1 Like

Hello Thanks for the reply, I actually mean't I want the script to be able to use both of them at the same time. Getting an input and also an argument, I want to give the user the choice to use either of them.

Thank you

if [ $# -gt 0 ]
then
    EXT=$1
else
    read -p "Enter Extension: " EXT
fi
1 Like

Thank you very much