Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
fi

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

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

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:

#/bin/sh
if ln "$1" "$2" ;
then
   unlink "$1"
fi

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

Here I might start with something along the lines of

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

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.

share|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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.