cannot move Directory not emptyRecursively compare directory contents by name, ignoring file...

Run Bash scripts in folder all at the same time

Users forgetting to regenerate PDF before sending it

Need a non-volatile memory IC with near unlimited read/write operations capability

Why did Old English lose both thorn and eth?

What could cause the sea level to massively decrease?

Is there a method for differentiating informative comments from commented out code?

Would a Nikon FG 20 film SLR camera take pictures without batteries?

Was it ever illegal to name a pig "Napoleon" in France?

What was the profession 芸者 (female entertainer) called in Germany?

Is there a strong legal guarantee that the U.S. can give to another country that it won't attack them?

Did Rabbi Akiva accept arguments from ignorance?

Four ships at the ocean with the same distance

What is the problem here?(all integers are irrational proof...i think so)

How does one acquire an undead eyeball encased in a gem?

What was this character's plan?

How to properly translate the key phrase of Erdoğan's 2016 letter to Putin, "kusura bakmasınlar," to Russian

Distinguish the explanations of Galadriel's test in LotR

Is there a saving throw against the Hex spell or the Hexblade's Curse feature?

What minifigure is this?

Why did Dumbledore ignore this line?

What factors could lead to bishops establishing monastic armies?

When I press the space bar it deletes the letters in front of it

Did right-wing politician Franz Josef Strauss ever explain why he gave a 3 billion loan to East Germany in 1983?

What does the multimeter dial do internally?



cannot move Directory not empty


Recursively compare directory contents by name, ignoring file extensions“cannot remove 'some_directory': Directory not empty”Script to split stringStripping directory paths to get file namesrm: Directory resources is not emptyrm -rf: cannot remove `/opt/jetty': Directory not emptymv: cannot remove directory: Directory not emptyHow to remove non english chars from a stringMove directory structure and preserve symlinkscannot permanently delete Xcode.app in trash, not even if with “sudo rm -rf” because directory is not empty?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ margin-bottom:0;
}







-1















Edited due to people want to know more then me just wanting to know how to deal with two directories with same names in different places and move one into another when mv will not allow it if files are in destanation area ..



they want to know what I am trying to do and why so ...



my script gets all of the directores within a parent dir then one at a time goes through each dir with the mp3 or flac files in it, then checks to see if resampling needs to be done by bitrate checking, then if bitrate greater then set resample bitrate it resamples the file, if not it skips it, next step : renaming all of the files by TAG information, if it does not have TAG information in the file itself I take it off the dir it is in then add that to it by artist dir and album dir or other means nevertheless the TAG information is added to file if needed then I use that META TAG informatio to rename the file.



song - artist.mp3



with this script I keep the files witin the orgial dirs when the script has completed working on all of the files within that artist dir it then needs to be move out of that partent dir so that when this script is ran again it will not go back over all of the files that have just been completed ...



so I have it rename that artist dir to the artist name because some of them have artist / album / discography @320MP3 crap all written within the Directory name -- so i clean it up bu just renaming it the artist off the META TAG Artsit info, then move it to another parent dir to keep all of the ones completed within that dir sys.



because I have many of same artist different albums dir names, as well as duplecate files within different dirs all in a parent dir. all the same artist with different named dirs -- Example -



1
Alice Cooper mad man/album name/Old-files



when complete it will be



Alice Cooper/album name/New-files



2
Alice Cooper whatever else is here/album/CD1/Old-iles



Alice Cooper whatever else is here/album/CD2/Old-files



when done it will be



Alice Cooper/album/CD1/New-iles



Alice Cooper/album/CD2/New-files



the steps :



loop one is to get dir name to work on



loop two is to go through every file within that dir structor and resmaple, reTag if needed, rename files , when all files are completed rename the dir to the artist name, then move it out of that parent dir into a different Parent dir to get it out of the way -



next dir within that parent dir
repeat steps



problem
when loop comes across a match for Album name that has already been renamed and move to the different parent dir it raises that error.



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


If Dir not moved then the script will just cycle through all of the files that are already completed waisting time as I have over 40,000 files it takes time to do this so I just move the complete dir out of there so on a second run of the script the next day it can start new



My Script it works but has a few bugs in it so it is still in testing mode so it has a lot of echo's in it : as well as I reuse code I 've written so you may see movie comments in there as well.



#!/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(.)/u1/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(.)/u1/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(.)/u1/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(.)/u1/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(.)/u1/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 "%rn" "${FILENAME}")"
#rateis="${rateme%.*}" # strip off period and everything to the right of it
echo
rateis="$(mp3info -r m -p "%rn" "${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 "%rn" "$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









share|improve this question

























  • What exactly are you trying to do? Why are you moving directories and not files? If the directory already exists, why would you move it instead of just moving the files it contains? The error you show only occurs when a directory of that name already exists.

    – terdon
    Nov 25 '15 at 15:18











  • I have a script that resamples all music files in dir's mp3 and flac then keeps the resampled files in orginal dir - then deletes the old file -- when it gets doen cycling through the entire dir and sub dirs resmapling all music files I need to get rid of that dir - move it out of the root dir with all of the rest of the OTHER dir that still have files that need to be resmapled. so when I run this script again it will not redo or try to redo what was already done.

    – uxserx-bw
    Nov 25 '15 at 17:07











  • what?? "I need to get rid of that dir" what dir?? ... "move it out of the root dir" that's not what you're trying above... "with all of the rest of the OTHER dir that still have files that need to be resampled" ... in the same directory tree? You'rve no resampled them, so why are you trying to move them? Look: Make a tree marked "original" and a different tree marked "resampled". At the start, all albums are in Original. Now, after each file you resample, move it to the "resampled" tree (or better yet, save it directly to that tree).

    – Otheus
    Nov 25 '15 at 17:20











  • it runs every file within that one dir first before touching it to rename it then moves to the next dir and does the same I am trying to now check the other parent dir for like name if true then move the contents into that same name dir then remove old dir then move on to a different dir to resample all of them files in it then do the same --

    – uxserx-bw
    Nov 25 '15 at 19:33











  • I have another script that resamlpes and make a different tree for all of the finished files but it gets me too many copys of same file due to orgianl dir has different name same songs in it, trying to clean it up and resamle and rid copies all at the same time :) its a work in progress ;)

    – uxserx-bw
    Nov 25 '15 at 19:35


















-1















Edited due to people want to know more then me just wanting to know how to deal with two directories with same names in different places and move one into another when mv will not allow it if files are in destanation area ..



they want to know what I am trying to do and why so ...



my script gets all of the directores within a parent dir then one at a time goes through each dir with the mp3 or flac files in it, then checks to see if resampling needs to be done by bitrate checking, then if bitrate greater then set resample bitrate it resamples the file, if not it skips it, next step : renaming all of the files by TAG information, if it does not have TAG information in the file itself I take it off the dir it is in then add that to it by artist dir and album dir or other means nevertheless the TAG information is added to file if needed then I use that META TAG informatio to rename the file.



song - artist.mp3



with this script I keep the files witin the orgial dirs when the script has completed working on all of the files within that artist dir it then needs to be move out of that partent dir so that when this script is ran again it will not go back over all of the files that have just been completed ...



so I have it rename that artist dir to the artist name because some of them have artist / album / discography @320MP3 crap all written within the Directory name -- so i clean it up bu just renaming it the artist off the META TAG Artsit info, then move it to another parent dir to keep all of the ones completed within that dir sys.



because I have many of same artist different albums dir names, as well as duplecate files within different dirs all in a parent dir. all the same artist with different named dirs -- Example -



1
Alice Cooper mad man/album name/Old-files



when complete it will be



Alice Cooper/album name/New-files



2
Alice Cooper whatever else is here/album/CD1/Old-iles



Alice Cooper whatever else is here/album/CD2/Old-files



when done it will be



Alice Cooper/album/CD1/New-iles



Alice Cooper/album/CD2/New-files



the steps :



loop one is to get dir name to work on



loop two is to go through every file within that dir structor and resmaple, reTag if needed, rename files , when all files are completed rename the dir to the artist name, then move it out of that parent dir into a different Parent dir to get it out of the way -



next dir within that parent dir
repeat steps



problem
when loop comes across a match for Album name that has already been renamed and move to the different parent dir it raises that error.



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


If Dir not moved then the script will just cycle through all of the files that are already completed waisting time as I have over 40,000 files it takes time to do this so I just move the complete dir out of there so on a second run of the script the next day it can start new



My Script it works but has a few bugs in it so it is still in testing mode so it has a lot of echo's in it : as well as I reuse code I 've written so you may see movie comments in there as well.



#!/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(.)/u1/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(.)/u1/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(.)/u1/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(.)/u1/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(.)/u1/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 "%rn" "${FILENAME}")"
#rateis="${rateme%.*}" # strip off period and everything to the right of it
echo
rateis="$(mp3info -r m -p "%rn" "${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 "%rn" "$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









share|improve this question

























  • What exactly are you trying to do? Why are you moving directories and not files? If the directory already exists, why would you move it instead of just moving the files it contains? The error you show only occurs when a directory of that name already exists.

    – terdon
    Nov 25 '15 at 15:18











  • I have a script that resamples all music files in dir's mp3 and flac then keeps the resampled files in orginal dir - then deletes the old file -- when it gets doen cycling through the entire dir and sub dirs resmapling all music files I need to get rid of that dir - move it out of the root dir with all of the rest of the OTHER dir that still have files that need to be resmapled. so when I run this script again it will not redo or try to redo what was already done.

    – uxserx-bw
    Nov 25 '15 at 17:07











  • what?? "I need to get rid of that dir" what dir?? ... "move it out of the root dir" that's not what you're trying above... "with all of the rest of the OTHER dir that still have files that need to be resampled" ... in the same directory tree? You'rve no resampled them, so why are you trying to move them? Look: Make a tree marked "original" and a different tree marked "resampled". At the start, all albums are in Original. Now, after each file you resample, move it to the "resampled" tree (or better yet, save it directly to that tree).

    – Otheus
    Nov 25 '15 at 17:20











  • it runs every file within that one dir first before touching it to rename it then moves to the next dir and does the same I am trying to now check the other parent dir for like name if true then move the contents into that same name dir then remove old dir then move on to a different dir to resample all of them files in it then do the same --

    – uxserx-bw
    Nov 25 '15 at 19:33











  • I have another script that resamlpes and make a different tree for all of the finished files but it gets me too many copys of same file due to orgianl dir has different name same songs in it, trying to clean it up and resamle and rid copies all at the same time :) its a work in progress ;)

    – uxserx-bw
    Nov 25 '15 at 19:35














-1












-1








-1








Edited due to people want to know more then me just wanting to know how to deal with two directories with same names in different places and move one into another when mv will not allow it if files are in destanation area ..



they want to know what I am trying to do and why so ...



my script gets all of the directores within a parent dir then one at a time goes through each dir with the mp3 or flac files in it, then checks to see if resampling needs to be done by bitrate checking, then if bitrate greater then set resample bitrate it resamples the file, if not it skips it, next step : renaming all of the files by TAG information, if it does not have TAG information in the file itself I take it off the dir it is in then add that to it by artist dir and album dir or other means nevertheless the TAG information is added to file if needed then I use that META TAG informatio to rename the file.



song - artist.mp3



with this script I keep the files witin the orgial dirs when the script has completed working on all of the files within that artist dir it then needs to be move out of that partent dir so that when this script is ran again it will not go back over all of the files that have just been completed ...



so I have it rename that artist dir to the artist name because some of them have artist / album / discography @320MP3 crap all written within the Directory name -- so i clean it up bu just renaming it the artist off the META TAG Artsit info, then move it to another parent dir to keep all of the ones completed within that dir sys.



because I have many of same artist different albums dir names, as well as duplecate files within different dirs all in a parent dir. all the same artist with different named dirs -- Example -



1
Alice Cooper mad man/album name/Old-files



when complete it will be



Alice Cooper/album name/New-files



2
Alice Cooper whatever else is here/album/CD1/Old-iles



Alice Cooper whatever else is here/album/CD2/Old-files



when done it will be



Alice Cooper/album/CD1/New-iles



Alice Cooper/album/CD2/New-files



the steps :



loop one is to get dir name to work on



loop two is to go through every file within that dir structor and resmaple, reTag if needed, rename files , when all files are completed rename the dir to the artist name, then move it out of that parent dir into a different Parent dir to get it out of the way -



next dir within that parent dir
repeat steps



problem
when loop comes across a match for Album name that has already been renamed and move to the different parent dir it raises that error.



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


If Dir not moved then the script will just cycle through all of the files that are already completed waisting time as I have over 40,000 files it takes time to do this so I just move the complete dir out of there so on a second run of the script the next day it can start new



My Script it works but has a few bugs in it so it is still in testing mode so it has a lot of echo's in it : as well as I reuse code I 've written so you may see movie comments in there as well.



#!/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(.)/u1/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(.)/u1/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(.)/u1/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(.)/u1/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(.)/u1/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 "%rn" "${FILENAME}")"
#rateis="${rateme%.*}" # strip off period and everything to the right of it
echo
rateis="$(mp3info -r m -p "%rn" "${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 "%rn" "$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









share|improve this question
















Edited due to people want to know more then me just wanting to know how to deal with two directories with same names in different places and move one into another when mv will not allow it if files are in destanation area ..



they want to know what I am trying to do and why so ...



my script gets all of the directores within a parent dir then one at a time goes through each dir with the mp3 or flac files in it, then checks to see if resampling needs to be done by bitrate checking, then if bitrate greater then set resample bitrate it resamples the file, if not it skips it, next step : renaming all of the files by TAG information, if it does not have TAG information in the file itself I take it off the dir it is in then add that to it by artist dir and album dir or other means nevertheless the TAG information is added to file if needed then I use that META TAG informatio to rename the file.



song - artist.mp3



with this script I keep the files witin the orgial dirs when the script has completed working on all of the files within that artist dir it then needs to be move out of that partent dir so that when this script is ran again it will not go back over all of the files that have just been completed ...



so I have it rename that artist dir to the artist name because some of them have artist / album / discography @320MP3 crap all written within the Directory name -- so i clean it up bu just renaming it the artist off the META TAG Artsit info, then move it to another parent dir to keep all of the ones completed within that dir sys.



because I have many of same artist different albums dir names, as well as duplecate files within different dirs all in a parent dir. all the same artist with different named dirs -- Example -



1
Alice Cooper mad man/album name/Old-files



when complete it will be



Alice Cooper/album name/New-files



2
Alice Cooper whatever else is here/album/CD1/Old-iles



Alice Cooper whatever else is here/album/CD2/Old-files



when done it will be



Alice Cooper/album/CD1/New-iles



Alice Cooper/album/CD2/New-files



the steps :



loop one is to get dir name to work on



loop two is to go through every file within that dir structor and resmaple, reTag if needed, rename files , when all files are completed rename the dir to the artist name, then move it out of that parent dir into a different Parent dir to get it out of the way -



next dir within that parent dir
repeat steps



problem
when loop comes across a match for Album name that has already been renamed and move to the different parent dir it raises that error.



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


If Dir not moved then the script will just cycle through all of the files that are already completed waisting time as I have over 40,000 files it takes time to do this so I just move the complete dir out of there so on a second run of the script the next day it can start new



My Script it works but has a few bugs in it so it is still in testing mode so it has a lot of echo's in it : as well as I reuse code I 've written so you may see movie comments in there as well.



#!/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(.)/u1/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(.)/u1/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(.)/u1/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(.)/u1/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(.)/u1/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 "%rn" "${FILENAME}")"
#rateis="${rateme%.*}" # strip off period and everything to the right of it
echo
rateis="$(mp3info -r m -p "%rn" "${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 "%rn" "$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






shell-script command-line directory






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 25 '15 at 18:31







uxserx-bw

















asked Nov 25 '15 at 14:37









uxserx-bwuxserx-bw

2552 gold badges6 silver badges18 bronze badges




2552 gold badges6 silver badges18 bronze badges













  • What exactly are you trying to do? Why are you moving directories and not files? If the directory already exists, why would you move it instead of just moving the files it contains? The error you show only occurs when a directory of that name already exists.

    – terdon
    Nov 25 '15 at 15:18











  • I have a script that resamples all music files in dir's mp3 and flac then keeps the resampled files in orginal dir - then deletes the old file -- when it gets doen cycling through the entire dir and sub dirs resmapling all music files I need to get rid of that dir - move it out of the root dir with all of the rest of the OTHER dir that still have files that need to be resmapled. so when I run this script again it will not redo or try to redo what was already done.

    – uxserx-bw
    Nov 25 '15 at 17:07











  • what?? "I need to get rid of that dir" what dir?? ... "move it out of the root dir" that's not what you're trying above... "with all of the rest of the OTHER dir that still have files that need to be resampled" ... in the same directory tree? You'rve no resampled them, so why are you trying to move them? Look: Make a tree marked "original" and a different tree marked "resampled". At the start, all albums are in Original. Now, after each file you resample, move it to the "resampled" tree (or better yet, save it directly to that tree).

    – Otheus
    Nov 25 '15 at 17:20











  • it runs every file within that one dir first before touching it to rename it then moves to the next dir and does the same I am trying to now check the other parent dir for like name if true then move the contents into that same name dir then remove old dir then move on to a different dir to resample all of them files in it then do the same --

    – uxserx-bw
    Nov 25 '15 at 19:33











  • I have another script that resamlpes and make a different tree for all of the finished files but it gets me too many copys of same file due to orgianl dir has different name same songs in it, trying to clean it up and resamle and rid copies all at the same time :) its a work in progress ;)

    – uxserx-bw
    Nov 25 '15 at 19:35



















  • What exactly are you trying to do? Why are you moving directories and not files? If the directory already exists, why would you move it instead of just moving the files it contains? The error you show only occurs when a directory of that name already exists.

    – terdon
    Nov 25 '15 at 15:18











  • I have a script that resamples all music files in dir's mp3 and flac then keeps the resampled files in orginal dir - then deletes the old file -- when it gets doen cycling through the entire dir and sub dirs resmapling all music files I need to get rid of that dir - move it out of the root dir with all of the rest of the OTHER dir that still have files that need to be resmapled. so when I run this script again it will not redo or try to redo what was already done.

    – uxserx-bw
    Nov 25 '15 at 17:07











  • what?? "I need to get rid of that dir" what dir?? ... "move it out of the root dir" that's not what you're trying above... "with all of the rest of the OTHER dir that still have files that need to be resampled" ... in the same directory tree? You'rve no resampled them, so why are you trying to move them? Look: Make a tree marked "original" and a different tree marked "resampled". At the start, all albums are in Original. Now, after each file you resample, move it to the "resampled" tree (or better yet, save it directly to that tree).

    – Otheus
    Nov 25 '15 at 17:20











  • it runs every file within that one dir first before touching it to rename it then moves to the next dir and does the same I am trying to now check the other parent dir for like name if true then move the contents into that same name dir then remove old dir then move on to a different dir to resample all of them files in it then do the same --

    – uxserx-bw
    Nov 25 '15 at 19:33











  • I have another script that resamlpes and make a different tree for all of the finished files but it gets me too many copys of same file due to orgianl dir has different name same songs in it, trying to clean it up and resamle and rid copies all at the same time :) its a work in progress ;)

    – uxserx-bw
    Nov 25 '15 at 19:35

















What exactly are you trying to do? Why are you moving directories and not files? If the directory already exists, why would you move it instead of just moving the files it contains? The error you show only occurs when a directory of that name already exists.

– terdon
Nov 25 '15 at 15:18





What exactly are you trying to do? Why are you moving directories and not files? If the directory already exists, why would you move it instead of just moving the files it contains? The error you show only occurs when a directory of that name already exists.

– terdon
Nov 25 '15 at 15:18













I have a script that resamples all music files in dir's mp3 and flac then keeps the resampled files in orginal dir - then deletes the old file -- when it gets doen cycling through the entire dir and sub dirs resmapling all music files I need to get rid of that dir - move it out of the root dir with all of the rest of the OTHER dir that still have files that need to be resmapled. so when I run this script again it will not redo or try to redo what was already done.

– uxserx-bw
Nov 25 '15 at 17:07





I have a script that resamples all music files in dir's mp3 and flac then keeps the resampled files in orginal dir - then deletes the old file -- when it gets doen cycling through the entire dir and sub dirs resmapling all music files I need to get rid of that dir - move it out of the root dir with all of the rest of the OTHER dir that still have files that need to be resmapled. so when I run this script again it will not redo or try to redo what was already done.

– uxserx-bw
Nov 25 '15 at 17:07













what?? "I need to get rid of that dir" what dir?? ... "move it out of the root dir" that's not what you're trying above... "with all of the rest of the OTHER dir that still have files that need to be resampled" ... in the same directory tree? You'rve no resampled them, so why are you trying to move them? Look: Make a tree marked "original" and a different tree marked "resampled". At the start, all albums are in Original. Now, after each file you resample, move it to the "resampled" tree (or better yet, save it directly to that tree).

– Otheus
Nov 25 '15 at 17:20





what?? "I need to get rid of that dir" what dir?? ... "move it out of the root dir" that's not what you're trying above... "with all of the rest of the OTHER dir that still have files that need to be resampled" ... in the same directory tree? You'rve no resampled them, so why are you trying to move them? Look: Make a tree marked "original" and a different tree marked "resampled". At the start, all albums are in Original. Now, after each file you resample, move it to the "resampled" tree (or better yet, save it directly to that tree).

– Otheus
Nov 25 '15 at 17:20













it runs every file within that one dir first before touching it to rename it then moves to the next dir and does the same I am trying to now check the other parent dir for like name if true then move the contents into that same name dir then remove old dir then move on to a different dir to resample all of them files in it then do the same --

– uxserx-bw
Nov 25 '15 at 19:33





it runs every file within that one dir first before touching it to rename it then moves to the next dir and does the same I am trying to now check the other parent dir for like name if true then move the contents into that same name dir then remove old dir then move on to a different dir to resample all of them files in it then do the same --

– uxserx-bw
Nov 25 '15 at 19:33













I have another script that resamlpes and make a different tree for all of the finished files but it gets me too many copys of same file due to orgianl dir has different name same songs in it, trying to clean it up and resamle and rid copies all at the same time :) its a work in progress ;)

– uxserx-bw
Nov 25 '15 at 19:35





I have another script that resamlpes and make a different tree for all of the finished files but it gets me too many copys of same file due to orgianl dir has different name same songs in it, trying to clean it up and resamle and rid copies all at the same time :) its a work in progress ;)

– uxserx-bw
Nov 25 '15 at 19:35










4 Answers
4






active

oldest

votes


















1














The mv command can do a variety of things depending on the types of its arguments, and there are some cases where it might not be able to do exactly what you want. It doesn't really handle merging two nonempty directories.



The documentation says this:




If the destination path exists, mv shall attempt to remove it. If this fails for any reason, mv shall write a diagnostic message to standard error, do nothing more with the current source_file, and go on to any remaining source_files.




And that's what you're running into here. mv dbyls /m/d/t/dbyls, where both arguments are directories, will try to remove /m/d/t/dbyls. If the directory is not empty, it will fail.



The typical workaround is to do mv dblys/* /m/d/t/dbyls, followed by rmdir dblys. Note that * might not match files that begin with ., depending on your shell environment.






share|improve this answer
























  • is there a way to catch that error so the script can know when to do that code you suggested --

    – uxserx-bw
    Nov 25 '15 at 16:29











  • @uxserx-bw Something like if test -d "$destdir" && ! rmdir -- "$destdir"; then echo "Directory $destdir is nonempty - try plan B"; fi. rmdir will not remove a directory if there's anything in it.

    – Mark Plotnick
    Nov 25 '15 at 16:36





















1














You could do it in two steps, first moving the files and then deleting the now empty parent directory:



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


In your concrete case, the fragment



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


can be replaced by something like this:



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





share|improve this answer


























  • its in a script that auto runs and hits random dir that throw that error -- need to know ow to catch that error and then handle it trying that code -- or a work around to have the sctipt just jump into the moved to dir that holds all of the modified files then rename the directoies, but that too may pose an error if another dir of the same name is already there too ---

    – uxserx-bw
    Nov 25 '15 at 16:40











  • @uxserx-bw I do not quite get what you are aiming at and why my suggestion does not work for you. To execute some special code in case the move failed, try movecommand || specialcommand. Is that what you meant? If not, could you update your question such that it explains what exactly the intended behavior of your script is?

    – klimpergeist
    Nov 25 '15 at 17:00











  • every time I try to give more information people just get more confused about what I am doing with my sctiprt because it does quite a few operations. I'm going to try and make it as clear as possiable what my script is doing then get to the part or parts I am having troble with -- please read it again in a few minutes as of this posting to you

    – uxserx-bw
    Nov 25 '15 at 17:17











  • @uxserx-bw It seems to me that moving the files instead of the directory as suggested above should work in both cases (note that I also added a mkdir, in case the new directory does not exist yet). So there is no real need to detect and handling any error. Or I'm still not quite getting the problem.

    – klimpergeist
    Nov 26 '15 at 8:32













  • I am resampling mp3/flac to mp3 then orginizing them now I am keepig them in same dir del the old file after renaming it -- then when that directory is fully completed with all of the mp3/flac files rename the parent dir to the artist name off META TAG info for duplicate dir with different parent names of same artist then moveing that whole completed dir with it's subdir's into a different parent tree Music/newDIr Artist name goes here/SubDIr's/all of the files now get rid of matching dir and all of its contents in OLD Parent DIr. Y? I have a lot of duplicate files with Different DIr names

    – uxserx-bw
    Nov 27 '15 at 16:14



















0














had it check to see if parent dir was already created in the different desanation base folder then if true just copy into it then delete the old dir else move the whole thing



                            ## 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





share|improve this answer































    0














    Option 1 - Use rsync + rm



    Though its man page doesn't document it, mv will refuse to rename a directory to another directory if the target directory contains files. This is a good thing in your case because you turn out to want to merge the content of the source into the target, which mv will not do.



    Use rsync -a backup/ backupArchives/ instead. After that rm -rf backup/*.



    Instead of using rsync, you also can do the classical



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


    which earns you more geek points.



    Option 2 - Use cp + rm



    Quick and dirty, if you know what you are doing:



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



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





    share








    New contributor



    Exequiel Barrirero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      Your Answer








      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "106"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: false,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: null,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f245437%2fcannot-move-directory-not-empty%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      4 Answers
      4






      active

      oldest

      votes








      4 Answers
      4






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      The mv command can do a variety of things depending on the types of its arguments, and there are some cases where it might not be able to do exactly what you want. It doesn't really handle merging two nonempty directories.



      The documentation says this:




      If the destination path exists, mv shall attempt to remove it. If this fails for any reason, mv shall write a diagnostic message to standard error, do nothing more with the current source_file, and go on to any remaining source_files.




      And that's what you're running into here. mv dbyls /m/d/t/dbyls, where both arguments are directories, will try to remove /m/d/t/dbyls. If the directory is not empty, it will fail.



      The typical workaround is to do mv dblys/* /m/d/t/dbyls, followed by rmdir dblys. Note that * might not match files that begin with ., depending on your shell environment.






      share|improve this answer
























      • is there a way to catch that error so the script can know when to do that code you suggested --

        – uxserx-bw
        Nov 25 '15 at 16:29











      • @uxserx-bw Something like if test -d "$destdir" && ! rmdir -- "$destdir"; then echo "Directory $destdir is nonempty - try plan B"; fi. rmdir will not remove a directory if there's anything in it.

        – Mark Plotnick
        Nov 25 '15 at 16:36


















      1














      The mv command can do a variety of things depending on the types of its arguments, and there are some cases where it might not be able to do exactly what you want. It doesn't really handle merging two nonempty directories.



      The documentation says this:




      If the destination path exists, mv shall attempt to remove it. If this fails for any reason, mv shall write a diagnostic message to standard error, do nothing more with the current source_file, and go on to any remaining source_files.




      And that's what you're running into here. mv dbyls /m/d/t/dbyls, where both arguments are directories, will try to remove /m/d/t/dbyls. If the directory is not empty, it will fail.



      The typical workaround is to do mv dblys/* /m/d/t/dbyls, followed by rmdir dblys. Note that * might not match files that begin with ., depending on your shell environment.






      share|improve this answer
























      • is there a way to catch that error so the script can know when to do that code you suggested --

        – uxserx-bw
        Nov 25 '15 at 16:29











      • @uxserx-bw Something like if test -d "$destdir" && ! rmdir -- "$destdir"; then echo "Directory $destdir is nonempty - try plan B"; fi. rmdir will not remove a directory if there's anything in it.

        – Mark Plotnick
        Nov 25 '15 at 16:36
















      1












      1








      1







      The mv command can do a variety of things depending on the types of its arguments, and there are some cases where it might not be able to do exactly what you want. It doesn't really handle merging two nonempty directories.



      The documentation says this:




      If the destination path exists, mv shall attempt to remove it. If this fails for any reason, mv shall write a diagnostic message to standard error, do nothing more with the current source_file, and go on to any remaining source_files.




      And that's what you're running into here. mv dbyls /m/d/t/dbyls, where both arguments are directories, will try to remove /m/d/t/dbyls. If the directory is not empty, it will fail.



      The typical workaround is to do mv dblys/* /m/d/t/dbyls, followed by rmdir dblys. Note that * might not match files that begin with ., depending on your shell environment.






      share|improve this answer













      The mv command can do a variety of things depending on the types of its arguments, and there are some cases where it might not be able to do exactly what you want. It doesn't really handle merging two nonempty directories.



      The documentation says this:




      If the destination path exists, mv shall attempt to remove it. If this fails for any reason, mv shall write a diagnostic message to standard error, do nothing more with the current source_file, and go on to any remaining source_files.




      And that's what you're running into here. mv dbyls /m/d/t/dbyls, where both arguments are directories, will try to remove /m/d/t/dbyls. If the directory is not empty, it will fail.



      The typical workaround is to do mv dblys/* /m/d/t/dbyls, followed by rmdir dblys. Note that * might not match files that begin with ., depending on your shell environment.







      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 25 '15 at 15:54









      Mark PlotnickMark Plotnick

      19.4k2 gold badges42 silver badges69 bronze badges




      19.4k2 gold badges42 silver badges69 bronze badges













      • is there a way to catch that error so the script can know when to do that code you suggested --

        – uxserx-bw
        Nov 25 '15 at 16:29











      • @uxserx-bw Something like if test -d "$destdir" && ! rmdir -- "$destdir"; then echo "Directory $destdir is nonempty - try plan B"; fi. rmdir will not remove a directory if there's anything in it.

        – Mark Plotnick
        Nov 25 '15 at 16:36





















      • is there a way to catch that error so the script can know when to do that code you suggested --

        – uxserx-bw
        Nov 25 '15 at 16:29











      • @uxserx-bw Something like if test -d "$destdir" && ! rmdir -- "$destdir"; then echo "Directory $destdir is nonempty - try plan B"; fi. rmdir will not remove a directory if there's anything in it.

        – Mark Plotnick
        Nov 25 '15 at 16:36



















      is there a way to catch that error so the script can know when to do that code you suggested --

      – uxserx-bw
      Nov 25 '15 at 16:29





      is there a way to catch that error so the script can know when to do that code you suggested --

      – uxserx-bw
      Nov 25 '15 at 16:29













      @uxserx-bw Something like if test -d "$destdir" && ! rmdir -- "$destdir"; then echo "Directory $destdir is nonempty - try plan B"; fi. rmdir will not remove a directory if there's anything in it.

      – Mark Plotnick
      Nov 25 '15 at 16:36







      @uxserx-bw Something like if test -d "$destdir" && ! rmdir -- "$destdir"; then echo "Directory $destdir is nonempty - try plan B"; fi. rmdir will not remove a directory if there's anything in it.

      – Mark Plotnick
      Nov 25 '15 at 16:36















      1














      You could do it in two steps, first moving the files and then deleting the now empty parent directory:



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


      In your concrete case, the fragment



      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


      can be replaced by something like this:



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





      share|improve this answer


























      • its in a script that auto runs and hits random dir that throw that error -- need to know ow to catch that error and then handle it trying that code -- or a work around to have the sctipt just jump into the moved to dir that holds all of the modified files then rename the directoies, but that too may pose an error if another dir of the same name is already there too ---

        – uxserx-bw
        Nov 25 '15 at 16:40











      • @uxserx-bw I do not quite get what you are aiming at and why my suggestion does not work for you. To execute some special code in case the move failed, try movecommand || specialcommand. Is that what you meant? If not, could you update your question such that it explains what exactly the intended behavior of your script is?

        – klimpergeist
        Nov 25 '15 at 17:00











      • every time I try to give more information people just get more confused about what I am doing with my sctiprt because it does quite a few operations. I'm going to try and make it as clear as possiable what my script is doing then get to the part or parts I am having troble with -- please read it again in a few minutes as of this posting to you

        – uxserx-bw
        Nov 25 '15 at 17:17











      • @uxserx-bw It seems to me that moving the files instead of the directory as suggested above should work in both cases (note that I also added a mkdir, in case the new directory does not exist yet). So there is no real need to detect and handling any error. Or I'm still not quite getting the problem.

        – klimpergeist
        Nov 26 '15 at 8:32













      • I am resampling mp3/flac to mp3 then orginizing them now I am keepig them in same dir del the old file after renaming it -- then when that directory is fully completed with all of the mp3/flac files rename the parent dir to the artist name off META TAG info for duplicate dir with different parent names of same artist then moveing that whole completed dir with it's subdir's into a different parent tree Music/newDIr Artist name goes here/SubDIr's/all of the files now get rid of matching dir and all of its contents in OLD Parent DIr. Y? I have a lot of duplicate files with Different DIr names

        – uxserx-bw
        Nov 27 '15 at 16:14
















      1














      You could do it in two steps, first moving the files and then deleting the now empty parent directory:



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


      In your concrete case, the fragment



      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


      can be replaced by something like this:



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





      share|improve this answer


























      • its in a script that auto runs and hits random dir that throw that error -- need to know ow to catch that error and then handle it trying that code -- or a work around to have the sctipt just jump into the moved to dir that holds all of the modified files then rename the directoies, but that too may pose an error if another dir of the same name is already there too ---

        – uxserx-bw
        Nov 25 '15 at 16:40











      • @uxserx-bw I do not quite get what you are aiming at and why my suggestion does not work for you. To execute some special code in case the move failed, try movecommand || specialcommand. Is that what you meant? If not, could you update your question such that it explains what exactly the intended behavior of your script is?

        – klimpergeist
        Nov 25 '15 at 17:00











      • every time I try to give more information people just get more confused about what I am doing with my sctiprt because it does quite a few operations. I'm going to try and make it as clear as possiable what my script is doing then get to the part or parts I am having troble with -- please read it again in a few minutes as of this posting to you

        – uxserx-bw
        Nov 25 '15 at 17:17











      • @uxserx-bw It seems to me that moving the files instead of the directory as suggested above should work in both cases (note that I also added a mkdir, in case the new directory does not exist yet). So there is no real need to detect and handling any error. Or I'm still not quite getting the problem.

        – klimpergeist
        Nov 26 '15 at 8:32













      • I am resampling mp3/flac to mp3 then orginizing them now I am keepig them in same dir del the old file after renaming it -- then when that directory is fully completed with all of the mp3/flac files rename the parent dir to the artist name off META TAG info for duplicate dir with different parent names of same artist then moveing that whole completed dir with it's subdir's into a different parent tree Music/newDIr Artist name goes here/SubDIr's/all of the files now get rid of matching dir and all of its contents in OLD Parent DIr. Y? I have a lot of duplicate files with Different DIr names

        – uxserx-bw
        Nov 27 '15 at 16:14














      1












      1








      1







      You could do it in two steps, first moving the files and then deleting the now empty parent directory:



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


      In your concrete case, the fragment



      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


      can be replaced by something like this:



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





      share|improve this answer















      You could do it in two steps, first moving the files and then deleting the now empty parent directory:



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


      In your concrete case, the fragment



      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


      can be replaced by something like this:



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






      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Nov 27 '15 at 16:42

























      answered Nov 25 '15 at 14:43









      klimpergeistklimpergeist

      6215 silver badges17 bronze badges




      6215 silver badges17 bronze badges













      • its in a script that auto runs and hits random dir that throw that error -- need to know ow to catch that error and then handle it trying that code -- or a work around to have the sctipt just jump into the moved to dir that holds all of the modified files then rename the directoies, but that too may pose an error if another dir of the same name is already there too ---

        – uxserx-bw
        Nov 25 '15 at 16:40











      • @uxserx-bw I do not quite get what you are aiming at and why my suggestion does not work for you. To execute some special code in case the move failed, try movecommand || specialcommand. Is that what you meant? If not, could you update your question such that it explains what exactly the intended behavior of your script is?

        – klimpergeist
        Nov 25 '15 at 17:00











      • every time I try to give more information people just get more confused about what I am doing with my sctiprt because it does quite a few operations. I'm going to try and make it as clear as possiable what my script is doing then get to the part or parts I am having troble with -- please read it again in a few minutes as of this posting to you

        – uxserx-bw
        Nov 25 '15 at 17:17











      • @uxserx-bw It seems to me that moving the files instead of the directory as suggested above should work in both cases (note that I also added a mkdir, in case the new directory does not exist yet). So there is no real need to detect and handling any error. Or I'm still not quite getting the problem.

        – klimpergeist
        Nov 26 '15 at 8:32













      • I am resampling mp3/flac to mp3 then orginizing them now I am keepig them in same dir del the old file after renaming it -- then when that directory is fully completed with all of the mp3/flac files rename the parent dir to the artist name off META TAG info for duplicate dir with different parent names of same artist then moveing that whole completed dir with it's subdir's into a different parent tree Music/newDIr Artist name goes here/SubDIr's/all of the files now get rid of matching dir and all of its contents in OLD Parent DIr. Y? I have a lot of duplicate files with Different DIr names

        – uxserx-bw
        Nov 27 '15 at 16:14



















      • its in a script that auto runs and hits random dir that throw that error -- need to know ow to catch that error and then handle it trying that code -- or a work around to have the sctipt just jump into the moved to dir that holds all of the modified files then rename the directoies, but that too may pose an error if another dir of the same name is already there too ---

        – uxserx-bw
        Nov 25 '15 at 16:40











      • @uxserx-bw I do not quite get what you are aiming at and why my suggestion does not work for you. To execute some special code in case the move failed, try movecommand || specialcommand. Is that what you meant? If not, could you update your question such that it explains what exactly the intended behavior of your script is?

        – klimpergeist
        Nov 25 '15 at 17:00











      • every time I try to give more information people just get more confused about what I am doing with my sctiprt because it does quite a few operations. I'm going to try and make it as clear as possiable what my script is doing then get to the part or parts I am having troble with -- please read it again in a few minutes as of this posting to you

        – uxserx-bw
        Nov 25 '15 at 17:17











      • @uxserx-bw It seems to me that moving the files instead of the directory as suggested above should work in both cases (note that I also added a mkdir, in case the new directory does not exist yet). So there is no real need to detect and handling any error. Or I'm still not quite getting the problem.

        – klimpergeist
        Nov 26 '15 at 8:32













      • I am resampling mp3/flac to mp3 then orginizing them now I am keepig them in same dir del the old file after renaming it -- then when that directory is fully completed with all of the mp3/flac files rename the parent dir to the artist name off META TAG info for duplicate dir with different parent names of same artist then moveing that whole completed dir with it's subdir's into a different parent tree Music/newDIr Artist name goes here/SubDIr's/all of the files now get rid of matching dir and all of its contents in OLD Parent DIr. Y? I have a lot of duplicate files with Different DIr names

        – uxserx-bw
        Nov 27 '15 at 16:14

















      its in a script that auto runs and hits random dir that throw that error -- need to know ow to catch that error and then handle it trying that code -- or a work around to have the sctipt just jump into the moved to dir that holds all of the modified files then rename the directoies, but that too may pose an error if another dir of the same name is already there too ---

      – uxserx-bw
      Nov 25 '15 at 16:40





      its in a script that auto runs and hits random dir that throw that error -- need to know ow to catch that error and then handle it trying that code -- or a work around to have the sctipt just jump into the moved to dir that holds all of the modified files then rename the directoies, but that too may pose an error if another dir of the same name is already there too ---

      – uxserx-bw
      Nov 25 '15 at 16:40













      @uxserx-bw I do not quite get what you are aiming at and why my suggestion does not work for you. To execute some special code in case the move failed, try movecommand || specialcommand. Is that what you meant? If not, could you update your question such that it explains what exactly the intended behavior of your script is?

      – klimpergeist
      Nov 25 '15 at 17:00





      @uxserx-bw I do not quite get what you are aiming at and why my suggestion does not work for you. To execute some special code in case the move failed, try movecommand || specialcommand. Is that what you meant? If not, could you update your question such that it explains what exactly the intended behavior of your script is?

      – klimpergeist
      Nov 25 '15 at 17:00













      every time I try to give more information people just get more confused about what I am doing with my sctiprt because it does quite a few operations. I'm going to try and make it as clear as possiable what my script is doing then get to the part or parts I am having troble with -- please read it again in a few minutes as of this posting to you

      – uxserx-bw
      Nov 25 '15 at 17:17





      every time I try to give more information people just get more confused about what I am doing with my sctiprt because it does quite a few operations. I'm going to try and make it as clear as possiable what my script is doing then get to the part or parts I am having troble with -- please read it again in a few minutes as of this posting to you

      – uxserx-bw
      Nov 25 '15 at 17:17













      @uxserx-bw It seems to me that moving the files instead of the directory as suggested above should work in both cases (note that I also added a mkdir, in case the new directory does not exist yet). So there is no real need to detect and handling any error. Or I'm still not quite getting the problem.

      – klimpergeist
      Nov 26 '15 at 8:32







      @uxserx-bw It seems to me that moving the files instead of the directory as suggested above should work in both cases (note that I also added a mkdir, in case the new directory does not exist yet). So there is no real need to detect and handling any error. Or I'm still not quite getting the problem.

      – klimpergeist
      Nov 26 '15 at 8:32















      I am resampling mp3/flac to mp3 then orginizing them now I am keepig them in same dir del the old file after renaming it -- then when that directory is fully completed with all of the mp3/flac files rename the parent dir to the artist name off META TAG info for duplicate dir with different parent names of same artist then moveing that whole completed dir with it's subdir's into a different parent tree Music/newDIr Artist name goes here/SubDIr's/all of the files now get rid of matching dir and all of its contents in OLD Parent DIr. Y? I have a lot of duplicate files with Different DIr names

      – uxserx-bw
      Nov 27 '15 at 16:14





      I am resampling mp3/flac to mp3 then orginizing them now I am keepig them in same dir del the old file after renaming it -- then when that directory is fully completed with all of the mp3/flac files rename the parent dir to the artist name off META TAG info for duplicate dir with different parent names of same artist then moveing that whole completed dir with it's subdir's into a different parent tree Music/newDIr Artist name goes here/SubDIr's/all of the files now get rid of matching dir and all of its contents in OLD Parent DIr. Y? I have a lot of duplicate files with Different DIr names

      – uxserx-bw
      Nov 27 '15 at 16:14











      0














      had it check to see if parent dir was already created in the different desanation base folder then if true just copy into it then delete the old dir else move the whole thing



                                  ## 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





      share|improve this answer




























        0














        had it check to see if parent dir was already created in the different desanation base folder then if true just copy into it then delete the old dir else move the whole thing



                                    ## 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





        share|improve this answer


























          0












          0








          0







          had it check to see if parent dir was already created in the different desanation base folder then if true just copy into it then delete the old dir else move the whole thing



                                      ## 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





          share|improve this answer













          had it check to see if parent dir was already created in the different desanation base folder then if true just copy into it then delete the old dir else move the whole thing



                                      ## 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






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 25 '15 at 22:31









          uxserx-bwuxserx-bw

          2552 gold badges6 silver badges18 bronze badges




          2552 gold badges6 silver badges18 bronze badges























              0














              Option 1 - Use rsync + rm



              Though its man page doesn't document it, mv will refuse to rename a directory to another directory if the target directory contains files. This is a good thing in your case because you turn out to want to merge the content of the source into the target, which mv will not do.



              Use rsync -a backup/ backupArchives/ instead. After that rm -rf backup/*.



              Instead of using rsync, you also can do the classical



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


              which earns you more geek points.



              Option 2 - Use cp + rm



              Quick and dirty, if you know what you are doing:



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



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





              share








              New contributor



              Exequiel Barrirero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.
























                0














                Option 1 - Use rsync + rm



                Though its man page doesn't document it, mv will refuse to rename a directory to another directory if the target directory contains files. This is a good thing in your case because you turn out to want to merge the content of the source into the target, which mv will not do.



                Use rsync -a backup/ backupArchives/ instead. After that rm -rf backup/*.



                Instead of using rsync, you also can do the classical



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


                which earns you more geek points.



                Option 2 - Use cp + rm



                Quick and dirty, if you know what you are doing:



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



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





                share








                New contributor



                Exequiel Barrirero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






















                  0












                  0








                  0







                  Option 1 - Use rsync + rm



                  Though its man page doesn't document it, mv will refuse to rename a directory to another directory if the target directory contains files. This is a good thing in your case because you turn out to want to merge the content of the source into the target, which mv will not do.



                  Use rsync -a backup/ backupArchives/ instead. After that rm -rf backup/*.



                  Instead of using rsync, you also can do the classical



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


                  which earns you more geek points.



                  Option 2 - Use cp + rm



                  Quick and dirty, if you know what you are doing:



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



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





                  share








                  New contributor



                  Exequiel Barrirero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.









                  Option 1 - Use rsync + rm



                  Though its man page doesn't document it, mv will refuse to rename a directory to another directory if the target directory contains files. This is a good thing in your case because you turn out to want to merge the content of the source into the target, which mv will not do.



                  Use rsync -a backup/ backupArchives/ instead. After that rm -rf backup/*.



                  Instead of using rsync, you also can do the classical



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


                  which earns you more geek points.



                  Option 2 - Use cp + rm



                  Quick and dirty, if you know what you are doing:



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



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






                  share








                  New contributor



                  Exequiel Barrirero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.







                  share


                  share






                  New contributor



                  Exequiel Barrirero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.








                  answered 6 mins ago









                  Exequiel BarrireroExequiel Barrirero

                  1012 bronze badges




                  1012 bronze badges




                  New contributor



                  Exequiel Barrirero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.




                  New contributor




                  Exequiel Barrirero is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                  Check out our Code of Conduct.
































                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Unix & Linux Stack Exchange!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2funix.stackexchange.com%2fquestions%2f245437%2fcannot-move-directory-not-empty%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      Taj Mahal Inhaltsverzeichnis Aufbau | Geschichte | 350-Jahr-Feier | Heutige Bedeutung | Siehe auch |...

                      Baia Sprie Cuprins Etimologie | Istorie | Demografie | Politică și administrație | Arii naturale...

                      Ciclooctatetraenă Vezi și | Bibliografie | Meniu de navigare637866text4148569-500570979m