Randy Banks
Randy Banks

Reputation: 371

Creating new tar file in current directory using single file

I'm writing a bash script that will check if a tar archive exists for a specific fileName.log, and if not, creating one with fileName.log. If a tar already exists, then I need to append fileName.log to it. I've never really worked with tar archives, aside from unzipping and unpacking .tar.gz files already given to me. I'm sure my problem is my syntax, but I'm having trouble figuring out the proper syntax based off the man page.

My code:

      # check if tarball for this file already exists. If so, append it. If not, create new tarball
      if [ -e "$newFile.tar" ];
      then
              echo "tar exists"
              tar -cvf "$newFile" "$newFile.tar"
      else
              echo "no tar exists"
              tar -rvf "$newFile"
      fi

Upvotes: 0

Views: 51

Answers (2)

swornabsent
swornabsent

Reputation: 994

Quite close, you have your -c and -r flags reversed (c created, r appends) and you want to put the filename first, like so:

if [ -e "$newFile.tar" ];
then
    echo "tar exists"
    tar -rvf "$newFile.tar" "$newFile"
else
    echo "no tar exists"
    tar -cvf "$newFile.tar" "$newFile"
fi

Upvotes: 1

Jörn Hees
Jörn Hees

Reputation: 3428

If you want to add $newfile to $newfile.tar maybe this way:

if [ -f "$newFile.tar" ];
then
        echo "tar exists"
        tar -rvf "$newFile.tar" "$newFile"
else
        echo "no tar exists"
        tar -cvf "$newFile.tar" "$newFile"
fi

Upvotes: 1

Related Questions