mv * folder (avoiding ‘cannot move’ error)

Anytime I want to move thousands of files to a new folder, I always encounter the same problem.

> mkdir my_folder
> mv * my_folder
mv: cannot move 'my_folder to a subdirectory of itself 'my_folder'

While I think that the error above is harmless (is it?) I am wondering if there is a way of avoiding it.

In case it matters, I am interested in a solution in zsh or one that works well across various shells.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

In zsh, with the extended_glob option enabled, you can use ~ to exclude patterns from globs, so you could use:

setopt extended_glob
mv -- *~my_folder my_folder

Or use the negation operator (still with extended_glob):

mv -- ^my_folder my_folder

Use braces to avoid typing the directory name twice:

mv -- {^,}my_folder

In bash (for other answer-seekers using it), you can use Ksh-style extended globs:

# If it's not already enabled
shopt -s extglob
mv -- !(my_folder) my_folder

You can also use that syntax in zsh if you enable the ksh_glob option.

Method 2

If there are only regular files apart from the new subdirectory, you could use find:

find . -type f -maxdepth 1 -exec mv {} my_folder ;

The -type f option will only find files (not dirs). -maxdepth 1 will keep find looking only in . (not recurs down into other dirs). The -exec … does your move.

In zsh, you can abbreviate this to

mv *(.) my_folder

Yes, the error is harmless.

Method 3

you can use :

mv * my_folder 2>/dev/null


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x