I am trying to make a script to rename a lot of files and directories in bulk. But I'm having trouble making it move through every file and subfile.
My script right now is this
#! /bin/bash
function _setname {
for file in "$@"
do
oldname=$(basename "${file}")
newname=$(echo "${oldname}" | tr '?%*:|' '_' )
echo "${newname}"
[ ! "${oldname}" = "${newname}" ] && mv "${oldname}" "${newname}"
done
}
function _recursivename {
for file in "$@"
do
currentpath="$(pwd)"
cd "$(dirname ${file})"
oldname="$(basename ${file})"
newname="$(_setname ${oldname})"
[ -d "${newname}" ] && _recursivename ./"${newname}"/*
cd "${currentpath}"
done
}
_recursivename "${@}"
exit
It breaks when it reaches the bottom of a directory tree and has to go back up, currentpath
has been overwritten and does not return to the beginning to look for a 2nd subdirectory.
I don't get why currentpath
gets overwritten, or how to do it properly.
EDIT: Just had to declare it local
, I thought it was declared local by defining it inside a function.
Variables used in a function are global. In other words, if a variable is assigned a value within a function, its value can be accessed by the caller. If you want to declare a variable that is used only within the function and should not accessible by its caller, this variable should be declared
local
. For example, you can put the following extra line in the beginning of your function_recursivename
:This is especially important for recursive functions that need to have their private copies of their local variables and which need to keep unique values in each invocation as in your case.