-1

I have to write a Bash script that will look to see if a file exists and move the file to a specific directory, then rename the file with an extension of .1 or .2 etc if .1 already exists. I feel like I have a good start on it but it's not recognizing the directory even though I can enter mv file destination directly and it works. Where am I going wrong?

#!/bin/bash
DESTINATION="~hbrown31/homework"
FILE=$1
if [ -e "$FILE" ]
 then
  for $FILE in 'ls|sort -g -r'
   do
    echo "File is being moved and renamed"
    NEWFILE="$DESTINATION""$FILE""."
    mv "$FILE" "$(NEWFILE + 1)"
   fi
 else
  echo "File does not exist"
fi
Heather
  • 25
  • 1
  • 2
  • 7

1 Answers1

0

It's not entirely clear to me what you want (I don't understand the 'ls|sort', but I think you are looking for something like:

#!/bin/bash
DEST=~hbrown31/homework  # Do not quote or the ~ will not be expanded

move() {
  suffix=0
  file="$DEST/$1"
  while test -e "$file"; do
    file="$DEST/$1.$((++suffix))"
  done
  mv -v "$1" "$file"
}

for x; do move "$x"; done

Note that some versions of mv do support options such as -b and --backup that may actually do most of the work for you.

William Pursell
  • 204,365
  • 48
  • 270
  • 300