I need to move a folder using unix mv command, but only if the target is in the same drive or the same filesystem. What would be the best approach?

migrated from stackoverflow.com Apr 29 '13 at 22:37

This question came from our site for professional and enthusiast programmers.

  • 1
    drive here you mean "device" ? e.g. same harddisk? – Kent Apr 29 '13 at 13:07
  • same device, yes – zapp Apr 29 '13 at 13:09
up vote 9 down vote accepted

Based on How to check if two directories or files belong to same filesystem (https://unix.stackexchange.com/):

In a shell script on Linux it can be done with stat:

stat -c "%d" /path  # returns the decimal device number

So you can:

file1=$(stat -c "%d" /path/file1)
file2=$(stat -c "%d" /path/file2)

and then compare.

You can also write like this:

if [ $(stat -c "%d" /path/file1) -eq $(stat -c "%d" /path/file1) ]
then
    # mv sentence
fi

Other option. Also taken from the Stackexchange question:

if [[ $(df -P /path/file1 | tail -1) = $(df -P /path/file2 | tail -1) ]]
then
    # echo "same filesystem"
    # mv sentence
fi
  • Do you think it's compatible across linux distributions? – zapp Apr 29 '13 at 13:07
  • Just for spreading the better practice, use $(...) instead of `...`. The later is deprecated in favor of the former. – Shahbaz Apr 29 '13 at 13:10
  • Thanks @Shahbaz , just edited it with your recommendation! – fedorqui Apr 29 '13 at 13:11
  • @zapp I don't know, should test it. My experience with stat tells me it is sometimes tricky, at least with SunOS. But being Linux I hope it is compatible. With my Ubuntu 12 it is fine. – fedorqui Apr 29 '13 at 13:13
  • this %d outputs different values for different dirs (same partition even) try with your / and /tmp – Kent Apr 29 '13 at 13:18

This is probably not the cleanest solution, but you could use the fact that hard links can't be created between drives.

ln /path1/file /path2/file 2> /dev/null
if [[ $? == 0 ]]
then
    rm /path1/file
fi

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.