In order to protect myself if I make a mistake in typing a directory/filename path, I am searching for a way to prevent mv from doing anything if the source and destination files exist on separate partitions.

I see no options in the man page. Google didn't seem to help. Maybe a something like

sourceDrive=something sourceFile
destinationDrive=something destinationFile

if [ $sourceDrive == $destinationDrive ]
   mv sourceFile destinationFile

I just need to find a way to get the partition the directory/file is on


You are almost certainly looking at writing a script to do this.

For files you could hardlink them and if that was successful, unlink the original. That won't work for directories (because most filesystems prohibit hardlinking directories).

Minimally tested, trivial script that might do it:

if ln "$1" "$2" ;
   unlink "$1"

The alternative is to check the filesystem associated with each path.

Here I might start with something along the lines of

#! /bin/sh
v1=$( $STAT -f "%d" "$1" )
v2=$( $STAT -f "%d" "$2" )
if [[ $v1 == $v2 ]]
    mv "$1" "$2"

WARNING! That has a bug if you specify the topmost directory of a filesystem as a target. Fixing the bug is subtle, but it might go like this: check if the destination already exists. If not touch it. Then stat the destination. If the copy fails and you had to create the target to test it, remove the target.

| improve this answer | |
  • The second option looks like it should do the trick. At least for stat version 7.4, use the "-c" flag for the "%d" format. Thank you kindly for your help. – user28173 Feb 14 '10 at 1:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy