Ayush Gupta
Ayush Gupta

Reputation: 9295

mv with wildcard fails with "No such file or directory" if no files match wildcard

I am running the following command:

mv logs/*.log logs/bak/

Now, when my logs folder contains a file which matches *.log, it works fine.

However, in case of no matching file, it throws error

mv: cannot stat 'logs/*.log': No such file or directory

How can I make this work?

EDIT I am trying to make this exit with a zero status code without doing anything so that I can use this in my build process

Upvotes: 5

Views: 1721

Answers (1)

Darren Smith
Darren Smith

Reputation: 2488

Use find instead of mv:

For example:

find logs -maxdepth 1 -type f -exec mv '{}' logs/bak  \;

... and while you are experimenting with this command, preface it with echo and/or use verbose:

find logs -maxdepth 1 -type f -exec echo mv '{}' logs/bak  \;
find logs -maxdepth 1 -type f -exec mv -v '{}' logs/bak  \;

Note the options:

-maxdepth 1 : prevent recursion into sub directories

-type f : only consider regular files

To match only files ending in .log you can add option:

-name *.log

EDIT BY OP

So, the final command comes out to be:

find logs -maxdepth 1 -type f -name \*.log -exec mv -v '{}' logs/bak  \;

Upvotes: 3

Related Questions