Skip to content

Instantly share code, notes, and snippets.

@pszemraj
Created September 16, 2025 15:35
Show Gist options
  • Save pszemraj/dde03df12d59548e826baddd40c38368 to your computer and use it in GitHub Desktop.
Save pszemraj/dde03df12d59548e826baddd40c38368 to your computer and use it in GitHub Desktop.
CLI/'programmatically' copy to clipboard from wsl

copy to clipboard from wsl

An adapted fn of what I use on ubuntu but leverages WSL exposing clip.exe to get stuff on your clipboard

# Copy file contents or stdin to clipboard
# Usage: cz [file]
#   cz file.txt  - copy file to clipboard
#   cmd | cz     - copy stdin to clipboard
# Fails on: binary files, files >10MB, non-existent files
cz() {
    if [ -z "$1" ]; then
        clip.exe
    elif [ -f "$1" ]; then
        # Check if it's a text file
        if file -b --mime-type "$1" | grep -q '^text/'; then
            # Check size (bail if over 10MB)
            size=$(stat -c%s "$1" 2>/dev/null || stat -f%z "$1" 2>/dev/null)
            if [ "$size" -gt 10485760 ]; then
                echo "Error: '$1' is ${size} bytes (>10MB). Too large for clipboard" >&2
                return 1
            fi
            clip.exe < "$1"
        else
            echo "Error: '$1' is not a text file" >&2
            return 1
        fi
    else
        echo "Error: '$1' not found" >&2
        return 1
    fi
}

simply put this at the bottom of your ~/.bashrc (or ~/.zshrc ) and open a new terminal or use source

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment