Domn Werner
Domn Werner

Reputation: 602

Bash Script To Check for Duplicate File Names from Command Line Arguments

I'm working on a shell script that will copy all the files from the command line to a directory. If the command line arguments contain any duplicate files, I want to prompt the user to either overwrite the existing file (it should now be in the directory), don't copy it, or rename it and then copy it.

What is the best way to approach this problem?

Here's some pseudocode of what I'm thinking:

for var in "$@"
do
  for file in "$dirName" #unsure about this syntax too
  do
    if [ file or directory with name "$fileName" exists]; then
       prompt user with options #i can handle this part :)
    else  
      mv $var $dirName
    fi
  done
done

Upvotes: 0

Views: 1493

Answers (1)

tripleee
tripleee

Reputation: 189936

You are overcomplicating things.

for var in "$@"
do
  if [ -e "$dirname/$var" ]; then
       prompt user with options #i can handle this part :)
  else  
      mv "$var" "$dirName"
  fi
done

Make sure you use adequate quoting everywhere, by the way. Variables which contain file names should basically always be double quoted.

Upvotes: 1

Related Questions