Swanand
Swanand

Reputation: 117

unix shell scripting- Using mv command in if condition

I want to move a file to a folder based on its file extension. example: if the file is .csv,it should move to COMPLETED folder , if the file has any extension other any .csv then it should move to REGULAR folder.

Below is my shell script and its not working. Can you let me know what is the problem with it?

#!/bin/bash
cd /apps/int/apd/$1/work

if ls /apps/int/apd/$1/work/*.csv &> /dev/null; then
    mv *.csv /apps/int/apd/$1/COMPLETED
else
    /apps/int/apd/$1/Regular
fi

Upvotes: 1

Views: 8447

Answers (2)

adimoise91
adimoise91

Reputation: 568

Change YOUR_PATH with your specific path and your path for /COMPLETED/ and /REGULAR/.

If I got what you wanted to explain i think your variables look like theese:

/YOUR_PATH/ = /apps/int/apd/$1/work
/COMPLETED/ = /apps/int/apd/$1/COMPLETED
/REGULAR/ = /apps/int/apd/$1/Regular    

You can try this. :)

#!/bin/bash

for filename in /YOUR_PATH/*;
do
    Path="$filename"
    extension="${filename##*.}"
    if [ "${extension}" = 'csv' ]; then
            mv $Path /COMPLETED/
    else
            mv $Path /REGULAR/
    fi
done

If you need anything pls leave a comment. :)

Upvotes: 0

Fazlin
Fazlin

Reputation: 2337

Why do you have to check the existence of *.csv files?

#!/bin/bash
cd /apps/int/apd/$1/work

mv *.csv /apps/int/apd/$1/COMPLETED 2>/dev/null
mv * /apps/int/apd/$1/Regular

Here first .csv files are moved to COMPLETED folder. Then rest of the files are moved to Regular folder.

I am assuming you have created COMPLETED and Regular folders.

Upvotes: 5

Related Questions