bashdirectoryrename

How can I rename a directory in bash, without overwriting or moving inside a pre-existing target?


I want to rename a directory, only if the target does not exist.

To do this the syntax should be

mv -n -T my/dir my/dirNew

Where -n means "don't overwrite" and -T means "don't move into the target". (https://askubuntu.com/a/763915/461996)

Details from man mv:

Unfortunately, -T is not an option on OSX, so any scripts making use of it won't work for OSX.

So, how can I rename a directory only if it won't overwrite one?

I've checked, and rename is not a standard I can depend on.


Solution

  • If its not necessary for you to achieve the same with mv command completely, you can simply do it like :

    [ ! -d "$destination_dir_name" ] && mv -n "$current_dir_name" "$destination_dir_name"
    

    [ ! -d "$destination_dir_name" ] would only evaluate to true if there is no such directory. If this evaluates to true && would confirm execution of mv "$current_dir_name" "$destination_dir_name".