Home > Net >  How to redirect existing file to a different directory in linux?
How to redirect existing file to a different directory in linux?

Time:11-18

I want to move files from directory 1 to directory 2, in that process if any file already exists in the destination folder it should instead move the file to directory 3.

I have create a script below but when ever file is skipped using -n parameter the result is true. Can someone let me know how to achieve this ?

   #!/bin/bash

    for file in dir1/*; do
      mv -n $file /dir2
      if [ $? != 0 ]; then
       mv $file /dir3
      fi
    done

CodePudding user response:

Suppose you have the following setup

mkdir dir{1,2,3}
touch dir1/test{1,2,3}
touch dir2/test2

The following code would move test1 and test3 to dir2 and test2 to dir3 out of dir1

for file in dir1/* ; 
do 
   fname="${file##*/}" ; 
   if [ -f "dir2/$fname" ]; then 
      mv "$file" dir3/ ; 
   else 
      mv "$file" dir2/ ; 
   fi 
done
  • Related