What is the point of mv -f when default behavior already overwrites files?

The usage of -f is more clearly described in the man page from 4BSD, which was where the -f and -i options were added:

If file2 already exists, it is removed before file1 is moved. If file2 has a mode which forbids writing, mv prints the mode and reads the standard input to obtain a line; if the line begins with y, the move takes place; if not, mv exits.

Options:

-i stands for interactive mode. Whenever a move is to supercede an existing file, the user is prompted by the name of the file followed by a question mark. If he answers with a line starting with 'y', the move continues. Any other reply prevents the move from occurring.

-f stands for force. This option overrides any mode restrictions or the -i switch.

An even more precise definition of how mv operates is given in the POSIX standard, which adds that -f only overrides -i if it occurs later in the command line.

So the default behavior is a bit different from -f. The default is to ask for confirmation only when the target isn't writable. (This behavior goes back at least as far as V4, where mv didn't take any options.) If the -i option is given, mv will additionally ask for confirmation whenever the target exists. The -f option will inhibit asking in both of those cases (if it occurs after any -i).


It's useful when having set the execution of mv to a sane default:

alias mv="mv -i"

When you then want to force a move, this will work:

mv -f

Since it's the last option in the expanded command that counts:

mv -i -f

This point is also mentioned in the GNU Coreutils manual.


It exists because (man mv)

If you specify more than one of -i, -f, -n, only the final one takes effect.

So, you can have a script/alias/function that always asks, but you can still override the option.

# alias
alias mv='mv -i'

# function
MV () { mv -i "$@" ; }

# script
#!/bin/bash
mv -i "$@"

A meaningful function/script would do something more, of course (e.g. log the action).

Tags:

Mv

History

Files