Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to mv files with specific extensions to newly created directories. This script moves files with all the extentions in all the newly created folders, which is not the intent. Instead, it should move extension-specific files to specific folders. How can I accomplish that?

for i in 1 2 3
do
    mkdir -p backup/ch0${i}
    if [ $? -eq ]; then
        echo "directory backup/ch0${i} created"
        for j in c h sh
        do
            count=0
            count=`expr $count + 1`
            if [ $count==i ]; then
                cp /home/owner/*.${j} backup/ch0${i}
                if [ $count!=i ]; then
                    continue;
                elif [ $? -ne 0 ]; then
                    break 2;
                fi
        done
    else
        echo "could not back up directory!!"
    fi 
done
share|improve this question

2 Answers 2

This should work:

backup_extensions()
{
    count=0
    while [ -n "$1" ]
    do
        let count+=1
        mkdir -p backup/ch0${count}
        cp /home/owner/*.${1} backup/ch0${count} || return 2
        shift
    done
}

backup_extensions c h sh
share|improve this answer
    
Hi l0b0, It worked..Thanks a lot!!! –  CuriousCoder Feb 7 '11 at 16:51
    
what does return 2 mean here ? –  CuriousCoder Feb 7 '11 at 17:48
    
Instead of answering 'It worked, thank's a lot!' you should vote l0b0 up (arrow up on the left) and probably select the check mark. –  user unknown Feb 10 '11 at 9:36
    
@CuriousCoder: return 2 is used to signal an error and stop the processing. If a cp fails, you don't want to keep on trying with the other files, because it's likely to be a serious error (out of disk space or missing target directory). –  l0b0 Jul 18 '11 at 12:26

I have not verified this, but it should do the job.

backups=( 1:c 2:h 3:sh )

for set in "${backups[@]}"; do
 IFS=":" read dir_bkup file_ext <<< "$set"
 if ! mkdir -p "backup/ch0$dir_bkup"; then
  echo  "Could not create "backup/ch0$dir_bkup. Skipping"
  continue
 fi
 cp "/home/owner/"*".$file_ext" "backup/$dir_bkup/"
done
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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