rename a dir making sure it doesn't exist already

1.3k views Asked by At

I was wondering about following

Let's say you have two directory's in linux dir1 and dir2. now when I do

mv dir1 dir2

then dir1 gets moved into dir2.

But what if I want to rename dir1 into dir2? And while dir2 already exist, let bash tell me so and ask me if I wish to override? or maybe just tell me that it can't be renamed for it already exists?

Is there a way for this?

2

There are 2 answers

1
Steephen On

If you use mv with option i it will prompt and check do you prefer to overwrite an existing directory or not if it is existing.

If dir1 and dir2 exists and you try as follows it will prompt you. If dir2 is not existing it will not prompt.

mv -i dir1 dir2
2
Kent On

what you can do is, use i and T options.

T will think the target as normal file, so that won't do "move into" if target dir existed; i will let you confirm. In your case, it would be:

mv -iT dir1 dir2

If dir2 doesn't exists, no confirmation message will show.

Note, if target dir2 is not empty, you cannot mv, even though you confirmed.

If you want to overwrite anyway, you need write a little function/script to do it.