#!/usr/bin/env bash
# haste - Simple, fast Hastebin-compatible paste uploader
# API: https://pste.us/api/v1/pastes
set -Eeuo pipefail
readonly API="https://pste.us/api/v1/pastes"
readonly NAME="${0##*/}"
QUIET=0
VERBOSE=0
CONTENT=""
FILE=""
usage() {
cat <<EOF
$NAME - Upload text to pste.us
Usage:
$NAME [options] [text]
command | $NAME
$NAME file.txt
Options:
-q, --quiet Print only the URL
-v, --verbose Show HTTP details
-h, --help Show this help
Examples:
$NAME "Hello World"
$NAME file.txt
cat file.txt | $NAME
$NAME -q "Hello World"
echo "Hello World" | $NAME
EOF
}
log() {
(( QUIET )) || printf '%s\n' "$*" >&2
}
die() {
printf '%s: %s\n' "$NAME" "$*" >&2
exit 1
}
command -v curl >/dev/null 2>&1 || die "curl is required"
command -v jq >/dev/null 2>&1 || die "jq is required"
# Parse options
while (($#)); do
case "$1" in
-q|--quiet)
QUIET=1
shift
;;
-v|--verbose)
VERBOSE=1
shift
;;
-h|--help)
usage
exit 0
;;
--)
shift
break
;;
-*)
die "Unknown option: $1"
;;
*)
if [[ -n "$FILE" || -n "$CONTENT" ]]; then
die "Only one input source is allowed"
fi
if [[ -f "$1" ]]; then
FILE="$1"
else
CONTENT="$1"
fi
shift
;;
esac
done
# Read input
if [[ -n "$FILE" ]]; then
CONTENT=$(cat -- "$FILE") || die "Unable to read file"
elif (($#)); then
CONTENT="$*"
elif [[ ! -t 0 ]]; then
CONTENT=$(cat) || die "Unable to read stdin"
else
usage
exit 1
fi
[[ -n "$CONTENT" ]] || die "Nothing to upload"
# Build JSON safely
PAYLOAD=$(jq -n --arg content "$CONTENT" \
'{content: $content, language: "text"}') ||
die "Failed to encode JSON"
# Upload
RESPONSE=$(mktemp) || die "Cannot create temporary file"
trap 'rm -f "$RESPONSE"' EXIT
log "Uploading paste..."
CURL_ARGS=(
--silent
--show-error
--fail-with-body
--location
--request POST
--header "Content-Type: application/json"
--header "Accept: application/json"
--data-binary "$PAYLOAD"
--output "$RESPONSE"
--write-out '%{http_code}'
--connect-timeout 10
--max-time 60
)
(( VERBOSE )) && CURL_ARGS+=(--verbose)
if ! STATUS=$(curl "${CURL_ARGS[@]}" "$API"); then
cat "$RESPONSE" >&2
die "Upload failed (HTTP ${STATUS:-unknown})"
fi
[[ "$STATUS" =~ ^2[0-9][0-9]$ ]] ||
die "Server returned HTTP $STATUS: $(cat "$RESPONSE")"
# Extract URL from API response
URL=$(jq -er '
.data.url //
.data.link //
.url //
.link //
empty
' "$RESPONSE" 2>/dev/null) ||
die "Could not find paste URL in response: $(cat "$RESPONSE")"
# Validate URL
[[ "$URL" == https://* ]] ||
die "Server returned an invalid URL: $URL"
# Output
printf '%s\n' "$URL"
# Clipboard (only in interactive mode)
if (( ! QUIET )) && [[ -t 1 ]]; then
if command -v wl-copy >/dev/null 2>&1; then
printf '%s' "$URL" | wl-copy
log "Copied to clipboard."
elif command -v xclip >/dev/null 2>&1; then
printf '%s' "$URL" | xclip -selection clipboard
log "Copied to clipboard."
elif command -v pbcopy >/dev/null 2>&1; then
printf '%s' "$URL" | pbcopy
log "Copied to clipboard."
fi
fi