johnslattery
11/2/2016 - 6:06 PM

Create a compressed copy of a file with an arbitrary name using xz, leaving the source file in place.

Create a compressed copy of a file with an arbitrary name using xz, leaving the source file in place.

archive_file() {
  local src_file="$1"
  local dst_file="$2"
  local -i exit_status=0
  local msg_type=

  [[ ! -e $dst_file ]] || {
    printf "%s: Destination file '%s' exists.\n" \
      "$FUNCNAME" "$dst_file" >&2
    return 1
  }

  xz --stdout - <"$src_file" >"$dst_file" || {
    exit_status="$?"
    case "$exit_status" in
      2)
        msg_type="Warning"
        ;;
      1 | *)
        msg_type="Error"
        ;;
    esac
    printf "%s: %s compressing file '%s' to file '%s'.\n" \
      "$FUNCNAME" "$msg_type" "$src_file" "$dst_file" >&2
    return "$exit_status"
  }

  touch --no-create --reference="$src_file" "$dst_file" || {
    exit_status="$?"
    printf "%s: touch failed setting times on file '%s'.\n" "$FUNCNAME" \
      "$dst_file" >&2
    return "$exit_status"
  }
}