无法移动 目录不为空

无法移动 目录不为空

编辑是因为人们想了解更多,而我只是想知道如何处理在不同位置具有相同名称的两个目录,并在文件位于目标区域时 mv 不允许时将一个目录移动到另一个目录中。

他们想知道我正在尝试做什么以及为什么这样做...

我的脚本获取父目录中的所有目录,然后一次遍历每个目录,其中包含 mp3 或 flac 文件,然后检查是否需要通过比特率检查来完成重采样,如果比特率更大,则设置重新采样比特率它会重新采样文件,如果不是,它会跳过它,下一步:通过标签信息重命名所有文件,如果文件本身没有标签信息,我将其从它所在的目录中取出,然后将其添加到其中艺术家目录和专辑目录或其他方式,但是如果需要,标签信息会添加到文件中,然后我使用该 META 标签信息来重命名该文件。

歌曲 - 艺术家.mp3

使用此脚本,当脚本完成对该艺术家目录中所有文件的处理后,我将文件保留在 orgial 目录中,然后需要将其移出该partent 目录,以便再次运行此脚本时它不会返回刚刚完成的所有文件......

所以我让它将该艺术家目录重命名为艺术家姓名,因为其中一些艺术家/专辑/唱片@320MP3废话都写在目录名称中 - 所以我清理它,只是将其重命名为META TAG Artsit信息中的艺术家,然后将其移动到另一个父目录,以保留该目录系统中完成的所有内容。

因为我有许多同一艺术家的不同专辑目录名称,以及不同目录中的重复文件都在父目录中。所有同一位艺术家具有不同的命名目录 - 示例 -

1 Alice Cooper mad man/专辑名称/旧档案

完成后它将是

艾丽丝·库珀/专辑名称/新文件

2 Alice Cooper 无论这里还有什么/专辑/CD1/Old-iles

爱丽丝·库珀(Alice Cooper)无论这里还有什么/专辑/CD2/旧文件

完成后将会是

艾丽丝·库珀/专辑/CD1/New-iles

艾丽丝·库珀/专辑/CD2/新文件

步骤 :

循环一是获取要处理的目录名称

循环二是遍历该目录结构体中的每个文件并重新映射,如果需要则重新标记,重命名文件,当所有文件完成后将目录重命名为艺术家姓名,然后将其从该父目录移出到不同的父目录中以获取它不妨碍 -

该父目录中的下一个目录重复步骤

当循环遇到已重命名的专辑名称的匹配项并移动到不同的父目录时,会引发该错误。

mv -f /from/here/sameNameDir    /to/here/ - that has the same name dir in it already

如果目录没有移动,那么脚本将循环遍历所有已经完成的文件,因为我有超过 40,000 个文件,所以需要时间来执行此操作,所以我只需将完整的目录移出那里,以便第二次运行第二天脚本就可以开始新的了

我的脚本可以工作,但有一些错误,因此它仍处于测试模式,因此其中有很多回声:并且我重用了我编写的代码,因此您也可以在其中看到电影评论。

#!/bin/bash

# started writting this on 11-24-2015


typeset -i FilesCountInSecondLoop    FilesInDirCount  filesLeftToDo   DirCountDn
let        FilesCountInSecondLoop=0  FilesInDirCount=0 filesLeftToDo=0 DirCountDn=0

typeset -i cycleThroughFilesCount    
let        cycleThroughFilesCount=0  

working_dir="/media/data/test-run"

move_to="/media/data/move_to_test"


# where you keep this script to run it in a terminal
# it is written so that you do not have to put it in the 
# working directory or directories to eliminate having to put
# a separate script in every folder to run it
##############################################

 script_dir="$HOME/working"


# max rate you want your orgianl files to be check for to be 
# resampled at

LameCheckRate=192

# bitrate you want your FLAC files coverted to mp3 in
# you can convert your FLAC to a higher rate then the
# resmapled mp3 if you like 
##################################

flac_convert_brate=192

# this is the FLAC settings it runs at
# flac -cd "$FILENAME" | lame -b "${flac_convert_brate}" - "$newFile" 


# LAME settings VBR low and High end

LameLowEnd=128 
LameHighEnd=192

# this is the LAME settings it runs at
##lame -V2 -b"${LameLowEnd}" -B"${LameHighEnd}" -F --vbr-new -m j -q2

#####################
## DO NOT CHANGE ####
runTime=1 ###########        
convertN=$1 #########
#####################
# gets amount of files wanted to resample on run
# from command line args
function rst(){

if [[ convertN -lt runTime ]]; then
  echo " you forgot to enter an amount to resample"
  ConvertNum=0
  exit 1
  else
  ConvertNum=$((convertN))
  return $ConvertNum #pass the var to space land

fi

}

rst

# var to keep amount of dirs desired to be done per run of script
# amount of files in the dir may not allow to get done in one day 
 amount_of_dir_to_work_on=$ConvertNum

echo ""$working_dir" START - creating list of files"

# get all of the names of the base dir to change name  a var containing ampunt of basenamedir in last place here 
#   amount_of_dir_to_work_on this is gotten off of the command line

    find "$working_dir" -mindepth 1 -maxdepth 1 -type d | while [ $DirCountDn  -lt $amount_of_dir_to_work_on ] ; 
        do read DIRNAME;
                    echo "$DIRNAME"



                #get list of all files in dir and sub dir's of current Dir to work off of

                    MAXMP3="$(find "$DIRNAME" -type f -name "*.mp3" | wc -l)"
                    MAXFLAC="$(find "$DIRNAME" -type f -name "*.flac" | wc -l)"

                    echo;echo;echo
                    echo "amount of mp3 "$MAXMP3" in "$DIRNAME""


                    FilesCountInSecondLoop=$(($MAXMP3 + $MAXFLAC))
                    filesLeftToDo="$FilesCountInSecondLoop" 



                    echo "Just starting off"
                    echo "MAXMP3 is               : "$MAXMP3""
                    echo "MAXFLAC is              : "$MAXFLAC""
                    echo "FilesCountInSecondLoop  : "$FilesCountInSecondLoop""
                    echo "Files left to do        : "$filesLeftToDo""
                    echo "cycleThroughFilesCount  : "$cycleThroughFilesCount""


                                                                      # MAXMP3 starts with a number 
                                                                       #  if not equle to 
                                                                       # cycleThroughFilesCount starts with zero         
    find "$DIRNAME" -type f -name "*.*" | while [ $FilesCountInSecondLoop -ne $cycleThroughFilesCount ] ;
        do read FILENAME;



                    #Directory to put the files back into it after resampling is completed  

                    r=$FILENAME

                    c=$FILENAME
                    xpath=${c%/*} 
                    xbase=${c##*/}
                    xfext=${xbase##*.}
                    xpref=${xbase%.*}
                    path=${xpath}
                    pref=${xpref}
                    ext=${xfext}


                    #checks to see if varitable is empty meaning no files to that extention to 
                    #resample are left to do --
                    if [ -z "$ext" ]; then 
                        echo "all Done - dar eay."
                        exit 1
                    fi

        #############################
        ############################
        ###
        ### GET RID OF EVERYTHING THAT IS NOT A MP3 OR FLAC FILE
        ###
        ##############################################################


        #Checks each movie file to see if it is just a not needed sample of the move to regain file space by deleting it

                    for file in "${path}" ; do 
                    #   echo "in for loop ext1 is -> "$ext"" 

                        if [[ "$ext" != 'flac' && "$ext" != 'mp3' && "ext" != 'jpg' ]]; then

                        #   echo "in loop if statment ext is -> "$ext""
                        #  echo "Removing "$FILENAME""

                        removeme="$FILENAME"
                        rm -v "$removeme"

                        # set a different ext type so that it will not go into following if statement due to it is still a movie extention
                        # causes it to skip over and go to next file
                        ## ext1="foobar"

                        let InIfLoop++
                    #   echo "in IF Loop ="${InIfLoop}""
                        fi
                            let inLoop++
                            #echo "inside of loop ="${inLoop}"" 
                    done

                        let leftLoop++
                        #echo "left loop count = "$leftLoop""


        ####################
        ###
        ### START ON MP3 or FLAC FILE
        ###
        ###############################################


        #echo "Extention off before into first if statment "${ext}""
        # echo

                    if [[ "${ext}" == 'mp3' || "${ext}" == 'flac' ]] ; then 

                        echo;echo
                        echo $FILENAME " Looking to resample this FILE now!"
                        echo;echo

        #############################################################
        #get the metadata tags off the mp3's using exiftool-perl
        #################

                ALBUM1="`exiftool  -Album  "$FILENAME" -p '$Album'`"
                ARTIST1="`exiftool -Artist "$FILENAME" -p '$Artist'`"
                SongName="`exiftool  -Title  "$FILENAME" -p '$Title'`"
                TRACK1=""
                TRACK2=""
                TRACK1="`exiftool "-Track Number" "$FILENAME" -p '$TrackNumber'`"
                TRACK2="`exiftool  -Track  "$FILENAME" -p '$Track'`"

                #GENRE1="`exiftool  -Genre "$FILENAME" -p '$Genre'`"
            #   echo "track 1  -> "$TRACK1""
            #   echo "track 2  -> "$TRACK2""
                #gets the number off the left side of file name if any then
                # hopefully fixs it to tag track number in file

                number=${pref//[^0-9 ]/}
                number=${number%% *}
                number=${number%/*}
        #removes leading white space on both ends of string
                number="$(echo -e "${number}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"

            #   echo "NUMBER IS now = "$number""

                if [ -z "${TRACK1}" ] && [ -z "${TRACK2}" ] ; then  
                    id3v2 -T "$number" "${FILENAME}"
                    echo "aftering adding track"
                    TRACK1="`exiftool "-Track Number" "$FILENAME" -p '$TrackNumber'`"
                    TRACK2="`exiftool  -Track  "$FILENAME" -p '$Track'`"
                    echo "this is track1 "$TRACK1""
                    echo "This is TRACK2 "$TRACK2""
                    echo

                fi



    #replaces all the crap and the spaces 
    #between the names with an underscore
    #"${x// /_}" meaning "${varName//search pattern/replace with}"


     echo "GETTING OFF TAGS"
    #echo
     echo "ARTIST1 going in is "$ARTIST1""
            newArt="${ARTIST1// / }"
            newArt="${newArt#/*}"
            newArt=${newArt//[^A-Za-z&0-9"'" ]/ }
            newArt="$(echo -e "${newArt}" | tr "[A-Z]" "[a-z]" | sed -e "s/\b\(.\)/\u\1/g")"
    #ensure only one space between each word
            newArt="$(echo -e "${newArt}" | sed -e 's/\s+/ /g')"
    #removes leading white space on both ends of string
            newArt="$(echo -e "${newArt}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
     echo "newArt comming out is -> "$newArt""


            newTit="${SongName// / }"
            newTit=${newTit//[^A-Za-z&0-9"'" ]/ }
    #Capitalizes each word
            newTit="$(echo -e "${newTit}" | tr "[A-Z]" "[a-z]" | sed -e "s/\b\(.\)/\u\1/g")"
    #ensure only one space between each word
            newTit="$(echo -e "${newTit}" | sed -e 's/\s+/ /g')"
    #removes leading white space on both ends of string
            newTit="$(echo -e "${newTit}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
    #echo "NEW TITLE comming out is"
     echo "$newTit"


    #echo "ALBUM1 going in is -> "$ALBUM1""
            newAlb="${ALBUM1%/*}" 
            newAlb=${newAlb//[^A-Za-z&0-9"'" ]/ }
    #Capitalizes each word
            newAlb="$(echo -e "${newAlb}" | tr "[A-Z]" "[a-z]" | sed -e "s/\b\(.\)/\u\1/g")"
    #ensure only one space between each word
            newAlb="$(echo -e "${newAlb}" | sed -e 's/\s+/ /g')"
    #removes leading white space on both ends of string
            newAlb="$(echo -e "${newAlb}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
     echo "newAlb commming out is -> "${newAlb}""
    #echo "DONE GETTING OFF TAGS"
    #echo
    #strip the orginal file name off the path from FILENAME
        c=$FILENAME
        xpath=${c%/*} 
        xbase=${c##*/}
        xfext=${xbase##*.}
        xpref=${xbase%.*}
        path=${xpath}
        pref=${xpref}
        ext=${xfext}

    ####################################

        c=$FILENAME

    ##############################
    # if MP3 has no needed tag information then 
    # strips names off of directory folders then uses them
    # as artist/band -- and album names in tags before renaming mp3 file
    ##########################
    # echo "GETTING OFF OF DIRECTORIES"

    # echo "STARTING TO EXTRACT DIRECTORIES NAMES"
        file=${c##*/}
        album1=${c#*"${c%/*/"$file"}"/}
        Artist=${album1%/*}
        Artist1=${c#*"${c%/*/"$album1"}"/}
        album=${album1%%/*}
        Artist2=${Artist1%%/*}
    #    echo "right here YO"
        dir=${FILENAME#*/*/*/*/} 
        dir=${dir//\/*}
        echo "$dir"
    #rename directory
        NewDirectoryName="$dir" 
    #   echo "$NewDirectoryName"
        NewDirectoryName=${NewDirectoryName%%'('*}
        NewDirectoryName=${NewDirectoryName%%'320cbr'*}
        NewDirectoryName=${NewDirectoryName%'[Bubanee]'*}
        NewDirectoryName=${NewDirectoryName%'MP3'*}
        NewDirectoryName=${NewDirectoryName%'2CD'*}
        NewDirectoryName=${NewDirectoryName%'Discography'*}
        NewDirectoryName=${NewDirectoryName%'discography'*}
        NewDirectoryName=${NewDirectoryName//[^A-Za-z ]/ }
    #Capitalizes each word
        NewDirectoryName="$(echo -e "${NewDirectoryName}" | tr "[A-Z]" "[a-z]" | sed -e "s/\b\(.\)/\u\1/g")"
    #ensure only one space between each word
        NewDirectoryName="$(echo -e "${NewDirectoryName}" | sed -e 's/\s+/ /g')"
    #removes leading white space on both ends of string
        NewDirectoryName="$(echo -e "${NewDirectoryName}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
    #echo "newAlb after striaghtening it up -> "${newAlb}""
    #   echo "NewDirectoryName is --- -> "$NewDirectoryName""
    #   echo

        e=$FILENAME
        xpath=${e%/*} 
        xbase=${e##*/}
        xfext=${xbase##*.}
        xpref=${xbase%.*}
        path1=${xpath}
        pref1=${xpref}
        ext1=${xfext}

    # echo "song off directory is -> "$pref1""
        songTitle="${pref1}"
        songTitle=${songTitle//[^A-Za-z&0-9"'" ]/ }
    #Capitalizes each word
        songTitle="$(echo -e "${songTitle}" | tr "[A-Z]" "[a-z]" | sed -e "s/\b\(.\)/\u\1/g")"
    #ensure only one space between each word
        songTitle="$(echo -e "${songTitle}" | sed -e 's/\s+/ /g')"
    #removes leading white space on both ends of string
        songTitle="$(echo -e "${songTitle}" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//')"
    #   echo "newAlb after striaghtening it up -> "${newAlb}""
    #   echo "new songTitle is -> "$songTitle""

    #  echo "DONE GETTING OFF OF DIRECTORIES"
    #echo;echo;
        if [ -z "$ALBUM1" ] ; then
            id3v2 -A "$newAlb1" "${FILENAME}"
            echo "tagging Album tag to file is -> "$newAlb1" "
            echo
        fi

        if [ -z "$ARTIST1" ] ; then
            id3v2 -a "$Artist" "${FILENAME}"
            echo "tagging Artist tag to file is -> "$Artist" "
            newArt=$Artist
            echo
        fi

        if [ -z "$SongName" ] ; then
            id3v2 -t "$songTitle" "${FILENAME}"
            echo "tagging Title tag to file is -> "$songTitle" "
            newTit=$songTitle 
            echo
        fi


    # MAKING NEW FILE NAME 
    ###########################


        ALBUM1="`exiftool  -Album  "$FILENAME" -p '$Album'`"

    #   echo "JFSDFSDFSDFSDFSDFSDFSDFSDFSDF"


        function GetArt () {
            if [[ ! -n "$ARTIST" ]]; then
                Art=$((ARTIST))
                #echo " got someting "

                return $Art #pass the var to space land
            fi
        }
            GetArt
          echo "this is the newAt justbefore making newFIle "$newArt""
        newFile=""${newTit}" - "${newArt}".mp3"

    # get the size of the Orginal File and keep for later use
        FileSize1="`exiftool '-File Size'  "$FILENAME" -p '$FileSize'`"


    #if song was already resampled it skips it then goes onto next one
        echo "******************************************************************"
    # echo "this is old file name about to be checked if matches new FileName"
    # echo "right here -> "$pref" new File name -> "${newFile%.*}""
    # echo
    ## REMOVE the Extention off of NewFile to check string
    #   if [[ "$pref" != "${newFile%.*}" ]] ; then

         if [[ "$pref" == "${newFile%.*}" ]] ; then
       echo;echo
                echo "This file -> :: "${newFile%.*}" " :: has already been done, skipping""

                let cycleThroughFilesCount++
                let filesLeftToDo--
                echo "amount of mp3   : "$MAXMP3" in "$DIRNAME""
                echo "MP 3 left to do : "$filesLeftToDo""
                echo "MP3 done        : "$cycleThroughFilesCount"" 
                echo;echo
         else

    #######################################
    #
    # CHECK BITRATE of MP3 = 192 - 160 vbr
    # CHOP OFF ENDING .00000
    # STORE IN VAR for checking value
    #########################################



        if [[ "${ext1}" == 'mp3' ]] ; then
    #rateme="$(mp3info -r a -p "%r\n" "${FILENAME}")"
    #rateis="${rateme%.*}" # strip off period and everything to the right of it
            echo
            rateis="$(mp3info -r m -p "%r\n" "${FILENAME}")"
            echo "Bitrate for "$pref1"."$ext1" is $rateis"
            echo    
            echo "LameCheckRate is "$LameCheckRate""
            echo
            echo "flac_convert_brate is "$flac_convert_brate""
            echo;echo
        fi
            echo;echo
        putback=${r%/*}
        echo "THIS IS PUT BACK DIR = "$putback""
echo;echo;  echo;echo;  echo;echo;  echo;echo;  echo;echo
    ##############################################################
    # Resampling FLAC with LAME 99.9.5  
    ###
    ##

        if [[ "${ext}" == 'flac' ]] ; then
            echo "got Dflack file  "${pref}"."${ext}""
            echo "converting to "${flac_convert_brate}" /kbps mp3"
            echo

            flac -cd "$FILENAME" | lame -h -b "${flac_convert_brate}" - "$newFile" 

            echo;echo;
    # get new bitrate and spit it out to the terminal
            rateis="$(mp3info -r m -p "%r\n" "$script_dir"/"${newFile}")"
            echo "Bitrate of .. $newFile   .. is .. $rateis .."
            echo;echo

            eyeD3 -A "$newAlb" "${script_dir}"/"${newFile}"
            echo "added "$newAlb" tag to file"

            eyeD3 -a "$newArt" "${script_dir}"/"${newFile}"
            echo "added "$newArt" tag to file"

            eyeD3 -t "$songTitle" "${script_dir}"/"${newFile}"
            echo "added "$songTitle" tag to file" 


        if [[ ! -n "${TRACK1}" ]] ; then        
            eyeD3 -n "$TRACK2" "${script_dir}"/"${newFile}"
            echo "added T2 - "$TRACK2" tag to file" 

        else 
            eyeD3 -n "$TRACK1" "${script_dir}"/"${newFile}"
            echo "added T1 - "$TRACK1" tag to file" 

        fi

            eyeD3 -G "$GENRE1"  "${script_dir}"/"${newFile}"
            echo "added "$GENRE1" tag to file" 
            echo;echo
            echo "after insert info "
            echo;echo "after reasiging FLAC resmapling" echo
            echo
        fi

    ##############################################################
    # Resampling MP3  with LAME 99.9.5  
    ###
    #flack file resampled into a MP3 falls through here and gets moved too
    # if MP3 is out of limits then re-sample it if not then send it through
        if [[ "${ext}" == 'mp3' ]] ; then
    # start bitrate       128        start bitrate       160
            if [[ "${rateis}" -gt "${LameCheckRate}" ]] ; then


        lame -V2 -b"${LameLowEnd}" -B"${LameHighEnd}" -F --vbr-new -m j -q2 "$FILENAME" "$newFile"
            echo
            echo "MOVING FILES NOW!"
            echo
            echo "$newFile"
            echo
    ## Resampled file is newFile located in script dir
            rm -v "${FILENAME}"
            echo;echo
            mv -v "${script_dir}"/"${newFile}" "${putback}"
            echo
            fileplace="${putback}"/"${newFile}"
            id3v2 -A "$newAlb" "${fileplace}"
            id3v2 -a "$newArt" "${fileplace}"
            id3v2 -t "$newTit" "${fileplace}"
            echo;echo "after move"
            exiftool "${putback}"/"${newFile}"

            let filesLeftToDo--
            let cycleThroughFilesCount++
            echo;echo "mp3's done "$cycleThroughFilesCount""
            else
    # if MP3 is within limits then skip resmapling then just make 
    # a copy to move it 
    # to new directory/folder
    ## WORKING SCRIPT DIRECTORY !
            echo;echo "is not needing resampling"
            echo "$pref1"."$ext"
            echo;echo "new file name is -> "${newFile}""
            echo

    #if old file name changed the change it
            compareme="${putback}"/"${newFile}"
            if [[ "${FILENAME}" != "${compareme}" ]] ; then

            mv -v "${FILENAME}" "${putback}"/"${newFile}"
            echo;echo "after not needing resample"
            echo
            exiftool "${putback}"/"${newFile}"

            let filesLeftToDo--
            let cycleThroughFilesCount++
            echo;echo "mp3 done "$cycleThroughFilesCount""

            fi
            echo;echo


            eyeD3 -A "$newAlb" "${putback}"/"${newFile}"
            echo "Non resampled stats"
    #exiftool "${script_dir}"/"${newFile}"

        fi

fi # end first if


            echo "Total MP3's Files are      : "$MAXMP3""
            echo "Files done so far is       : "$cycleThroughFilesCount""
            echo "MP3's left to do are       : "$filesLeftToDo""

# echo "After mp3 resampling file ->"
# exiftool "${script_dir}"/"${newFile}"

# I use EXIFTOOL because it works on FLAC files too for
# extracting the information
    echo;echo;





# get the size of the finished file to show differece in size of file
    echo "putback is --------  "$putback""
    checkme=""${putback}"/"${newFile}"" 
    FileSize2="`exiftool '-File Size' "$checkme" -p '$FileSize'`"


    fi


fi # end checking string for done file 


###########################################
## DO THE MATH ON MEGABYTES SAVED #########
###########################################

# if it cathces a KB file then it throws off the math. adding
# this keeps MB rounded up to the nearest whole one MB. 
    echo
    Hold1=$FileSize1
    Hold2=$FileSize2

    k1="${Hold1#* }"
    echo ""$k1" -- k1"

    if [[ "$k1" == 'kB' ]] ; then
        MB1=1
    else
        MB1="${FileSize1% *}"
    fi

    k2="${Hold2#* }"
    echo ""$k2" -- k2"

    if [[ "$k2" == 'kB' ]] ; then
        MB2=1
    else
        MB2="${FileSize2% *}"
    fi


# if it cannot stat file -- file unfound - bad file - then put a 
# zero in place of nothing to keep the total 
    if [[ "$FileSize1" == "" ]] ; then
        MB1=0
    fi

    if [[ "$FileSize2" == "" ]] ; then
        MB2=0
    fi

        echo "  "$MB1"  MB1 - start size"
        echo "- "$MB2"  MB2 - ending size"

# doing math on MB's
        totalSaveOnFile=`echo $MB1 - $MB2 | bc`
    echo "----------"
    echo "  "$totalSaveOnFile" MB - regained space" 
    echo "%%%%%%%%%%%%%%%"
    echo
    #maxSaved=$(( totalSaveOnFile + maxSaved ))


    maxSaved=`echo $totalSaveOnFile + $maxSaved | bc`
    echo
    echo "%%%%%%%%%%%%%%%%%%"
    echo;echo;echo
                            echo "***************************************"
                            echo;echo;echo





                            echo "AT IF STATMENTS"

                            echo "FILENAME is "$FILENAME""
                            NEWFILENAME=${FILENAME%/*}
                            #DIRNAME=${DIRNAME#*/*/*/*/} 
                            #DIRNAME=${DIRNAME//\/*}
                            echo "DIRNAME is "$DIRNAME""


                            echo "before if to do it"
                            echo "FilesCountInSecondLoop : "$FilesCountInSecondLoop""
                            echo "MAXMP3                 : "$MAXMP3""

                            if [[ "$FilesCountInSecondLoop" == "$cycleThroughFilesCount" ]] ; then

                                    echo " in if fileCount check"
                                    echo " NEWFILENAME is  "${NEWFILENAME}""
                                    echo "new file is "${newFile}""
                                    ARTIST1="`exiftool -Artist "${NEWFILENAME}"/"${newFile}" -p '$Artist'`"
                                    NewDirName="$ARTIST1"
                                    echo "new dir name is "$NewDirName""
                                    echo "this is MP3Count - "$MP3Count""
                                    #var names for dir nd paths and string compair
                                    OldDirName="$DIRNAME"
                                    echo;echo "OldDirName "$OldDirName""
                                    stringOldDir=${DIRNAME#*/*/*/*/}                                
                                    stringOldDir=${stringOldDir//\/*}
                                    echo;echo "stringOldDir "$stringOldDir""
                                    stringNewDir="$NewDirName"
                                    echo;echo "stringNewDir "$stringNewDir""
                                    oldDirPathNewName=""$working_dir"/"$NewDirName""
                                    echo;echo "oldDirPathNewName "$oldDirPathNewName""

                                 # if orginal dir name does not equals artist Tag name
                                 # change the dir to Artist Tag name then move it

                                 if [[ "$stringOldDir" != "$stringNewDir" ]] ; then  
                                    echo "not = "$stringOldDir" to "$stringNewDir""
                                            #change name of dir to artist/band name
                                                echo "mv OldDirName "$OldDirName" to "$oldDirPathNewName""
                                                echo "Working dir "$working_dir""

                                                #change old dir name to new dir name
                                                mv -v "$OldDirName" "$oldDirPathNewName"

                                                #then check to be sure root dir to move it to is there
                                                if [[ ! -d "$move_to" ]] ; then
                                                        echo "inside if more to dir is there"
                                                        mkdir -v "$move_to" 
                                                        #then move the new dir name to a different
                                                        # place for safe keeping
                                                        echo;echo "just befor move "
                                                        echo "oldDirPathNewName "$oldDirPathNewName" move to "$move_to""
                                                        mv -vf "$oldDirPathNewName" "$move_to" 
                                                else
                                                    echo "ELSE oldDirPathNewName "$oldDirPathNewName" move to "$move_to""
                                                    #if dir already created then just move the new dir there
                                                            mv -vf "$oldDirPathNewName" "$move_to"
                                                fi
                                fi

                        #if old dir name matches Artist Tag then insure more to dir is there then move it there

                                if [[ "$stringOldDir" == "$stringNewDir" ]] ; then  
                                  echo "Match strings "$stringOldDir" and "$stringNewDir""
                                    if [[ ! -d "move_to" ]] ; then
                                        mkdir -v "$move_to"
                                        mv -vf "$OldDirName" "$move_to" 
                                    else
                                        mv -fv "$OldDirName" "$move_to" 
                                    fi

                                fi
                        fi



    done
    let DirCountDn++
                echo "Dir Count Dn "$DirCountDn"" 
                echo "******************************************" 
                echo;echo;echo

done #FOR DIR Names

答案1

mv 命令可以根据其参数的类型执行多种操作,并且在某些情况下它可能无法完全执行您想要的操作。它并不真正处理合并两个非空目录。

文档说:

如果目标路径存在,mv 将尝试删除它。如果由于任何原因失败,mv 将向标准错误写入一条诊断消息,对当前源文件不执行任何操作,并继续处理任何剩余的源文件。

这就是你在这里遇到的情况。mv dbyls /m/d/t/dbyls,其中两个参数都是目录,将尝试删除/m/d/t/dbyls.如果目录不为空,则会失败。

典型的解决方法是先执行mv dblys/* /m/d/t/dbyls,然后执行rmdir dblys。请注意,*可能与以 开头的文件不匹配.,具体取决于您的 shell 环境。

答案2

您可以分两步完成,首先移动文件,然后删除现在空的父目录:

mkdir -p to/there
mv from/here/* to/there
rmdir from/here

在您的具体情况下,片段

if [[ "$stringOldDir" == "$stringNewDir" ]] ; then  
   echo "Match strings "$stringOldDir" and "$stringNewDir""
   if [[ ! -d "move_to" ]] ; then
     mkdir -v "$move_to"
     mv -vf "$OldDirName" "$move_to" 
   else
     mv -fv "$OldDirName" "$move_to" 
   fi
 fi

可以用这样的东西代替:

mkdir -p "$move_to/$OldDirName"
mv "$OldDirName"/* "$move_to/$OldDirName"
rmdir "$move_to/$OldDirName"

答案3

检查父目录是否已在不同的 desanation 基本文件夹中创建,如果为 true,则将其复制到其中,然后删除旧目录,否则移动整个目录

                            ## check to see if other parent dir  is there if not then make it so
                            if [[ ! -d "$move_to" ]] ; then
                                mkdir -v "$move_to"
                            fi

                        # if old dir does not match new dir name then change it

                                 if [[ "$stringOldDir" != "$stringNewDir" ]] ; then  
                                    echo "not = "$stringOldDir" to "$stringNewDir""


                                            #change name of dir to artist/band name
                                                echo "mv OldDirName "$OldDirName" to "$oldDirPathNewName""


                                                #change old dir name to new dir name
                                                mv -v "$OldDirName" "$oldDirPathNewName"
                                fi


                        #check if other parent dir and artist are there if not handle it

                                if [[ ! -d "$move_to"/"$stringNewDir" ]] ; then

                                            echo "inside ck if move to parent / artist to dir is there"
                                            echo
                                            echo ""$move_to"/"$stringNewDir" is not there moving "$stringNewDir""
                                            echo                                    
                                            #then move the new dir name to a different
                                            # place for safe keeping
                                            echo
                                            echo;echo "just befor move "
                                            echo
                                            echo "oldDirPathNewName "$oldDirPathNewName" move to "$move_to""
                                            echo            
                                            mv -vf "$oldDirPathNewName" "$move_to"/"$stringNewDir" 
                                            echo            

                                else
                                            echo ""$move_to"/"$stringNewDir" is there moving within it into"
                                            echo
                                            echo "$move_to"/"$stringNewDir"
                                            echo
                                            moveinsideof="$oldDirPathNewName"
                                            echo
                                            cp -Rv "${moveinsideof}"/* "$move_to"/"$stringNewDir" 
                                            echo
                                            rm -rv "$oldDirPathNewName"
                                fi

            fi      

答案4

选项 1 - 使用rsync + rm

尽管其手册页没有记录它,但mv如果目标目录包含文件,将拒绝将目录重命名为另一个目录。这对你来说是一件好事,因为你结果想要合并将源的内容放入目标中,这是mv不行的。

代替使用rsync -a backup/ backupArchives/。在那之后rm -rf backup/*

除了使用之外rsync,您还可以执行经典的操作

(cd backup && tar c .) | (cd backupArchives && tar xf -)

这将为您赢得更多极客积分。

选项 2 - 使用cp + rm

快速而肮脏,如果你知道自己在做什么:

cp -r ./backup/* ./backupArchives && rm -R ./backup/*

参考:https://askubuntu.com/questions/269775/mv-directory-not-empty/269818#269818

相关内容