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 "$@"
        oldname=$(basename "${file}")
        newname=$(echo "${oldname}" | tr '?%*:|' '_' )
        echo "${newname}"
        [ ! "${oldname}" = "${newname}" ] && mv "${oldname}" "${newname}"
function _recursivename {
    for file in "$@"
        cd "$(dirname ${file})"
        oldname="$(basename ${file})"
        newname="$(_setname ${oldname})"

        [ -d "${newname}" ] && _recursivename ./"${newname}"/*

        cd "${currentpath}"
_recursivename "${@}"

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.

  • 2
    Can you try to declare it as local? See: linux.die.net/abs-guide/localvar.html – FedonKadifeli Jun 12 at 10:19
  • Hey, that works, I was under the impression that just declaring the variable inside the function already made it local. – metichi Jun 12 at 10:26
  • @FedonKadifeli could you draw up an answer this way this can be resolved? – tatsu Jun 12 at 11:03

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:

local currentpath

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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