0

I wrote the following function to recursively rename files in some subdirectories:

rrename(){ find . -type f -name $1 -execdir mv {} $2 ';' }

This works fine when I call it like this:

rrename '*.md' renamed.md

however, I would rather not need to include the single quotes and call it like this instead:

rrename *.md renamed.md

I tried this but it still does not work:

rrename(){ find . -type f -name "'$1'" -execdir mv {} $2 ';' }

HOw can I fix it?

3
  • (1) Quote right. (2) Magic alias, see Applications here. Commented Oct 6, 2022 at 14:25
  • Are you sure you are posting what did work? I have tested your initial function and command, and I couldn't make it work properly. Please post the actual code that worked. Then just saying "it [still] does not work" is not very helpful: please post the result of the commands. And last, I'm not sure what are trying to do, but 1) why do want to avoid the single quotes? They ensure that no expansion can occur on *.md; and 2) if you have several files ending with .md in the same directory they will all be both renamed to renamed.md (i.e. only one will be kept, the other ones will be lost)
    – PierU
    Commented Oct 6, 2022 at 14:51
  • Your definition of rrename is not syntactically valid in Bash. It's not the function cannot be used, it cannot be defined in the first place. The definition would work in Zsh. Your blatantly unquoted $1 and $2 are wrong in Bash, they can be safely left unquoted in Zsh. Despite the bash tag, is your shell Zsh? Commented Oct 6, 2022 at 15:21

1 Answer 1

1

When *.md is unquoted, the pattern gets expanded before the arguments are handed to the function. In that case, $1 is the first markdown file in the current directory and $2 is the second one. If you want to pass a pattern to a function, you must quote it.

Similarly, in the function, when $1 is unquoted it will be expanded (to markdown files in the current directory) before find is launched.

Do it this way:

rrename() { find . -type f -name "$1" -execdir mv {} "$2" ';' }
# ...............................^..^................^..^

rrename '*.md' renamed.md
# ......^....^

All those quotes are necessary.


Tangentially, what happens when there are multiple *.md files in a particular directory? All of them are getting renamed to one file.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .