Home » Questions » Computers [ Ask a new question ]

Don't move a directory/file if src and dest are on different partitions

Don't move a directory/file if src and dest are on different partitions

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.

Asked by: Guest | Views: 152
Total answers/comments: 1
Guest [Entry]

"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."