Skip to content

Instantly share code, notes, and snippets.

@ivystopia
Created February 21, 2026 13:04
Show Gist options
  • Select an option

  • Save ivystopia/6412f01fd8db48bdd327d2f88a1f09b6 to your computer and use it in GitHub Desktop.

Select an option

Save ivystopia/6412f01fd8db48bdd327d2f88a1f09b6 to your computer and use it in GitHub Desktop.
Linux script: copy image from URL to clipboard
#!/usr/bin/env bash
# Copy an image from an HTTP(S) URL to the clipboard (Wayland/X11).
# Usage examples:
# copy-image-from-url https://example.com/image.png
# echo "https://example.com/image.png" | copy-image-from-url
set -euo pipefail
quit_with_error() {
echo "$*" >&2
exit 1
}
usage() {
cat >&2 <<'EOF'
Usage:
copy-image-from-url <http(s)-url>
echo "<http(s)-url>" | copy-image-from-url
EOF
exit 2
}
# Check for required commands
for cmd in curl file; do
command -v "$cmd" >/dev/null 2>&1 || quit_with_error "Missing required command: $cmd"
done
if ! command -v wl-copy >/dev/null 2>&1 && ! command -v xclip >/dev/null 2>&1; then
quit_with_error "Need wl-copy (Wayland) or xclip (X11) to write to clipboard."
fi
# Get the URL from the first argument
url="${1:-}"
# When no argument is provided, read from stdin (pipe)
if [[ -z "$url" ]]; then
if [[ -t 0 ]]; then
usage
fi
IFS= read -r url || true
fi
# Validate the URL format (basic check)
case "$url" in
http://*|https://*) ;;
*) quit_with_error "Input is not an http(s) URL" ;;
esac
# Create a temporary directory for downloading the image (gets cleaned up on exit)
tmp="$(mktemp "${TMPDIR:-/tmp}/copy-image-from-url.XXXXXX")"
cleanup() { rm -f "$tmp"; }
trap cleanup EXIT INT TERM
# Download the URL
curl -fsSL "$url" -o "$tmp"
# Check the MIME type of the downloaded file to ensure it's an image
if [[ $(file -b --mime-type "$tmp" 2>/dev/null || true) != image/* ]]; then
echo "Downloaded file is not an image." >&2
echo "Saved at: $tmp" >&2
trap - EXIT INT TERM
exit 3
fi
# Copy the image to the clipboard using wl-copy (Wayland) or xclip (X11)
if [[ -n "${WAYLAND_DISPLAY:-}" ]] && command -v wl-copy >/dev/null 2>&1; then
wl-copy --type "$mime" <"$tmp"
elif command -v xclip >/dev/null 2>&1; then
xclip -selection clipboard -t "$mime" -i "$tmp"
else
quit_with_error "Need wl-copy (Wayland) or xclip (X11) to write to clipboard."
fi
echo "Image copied to clipboard ($mime). Paste with Ctrl+V."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment