Skip to content

Instantly share code, notes, and snippets.

@goeko
Created November 26, 2024 21:54
Show Gist options
  • Save goeko/b9b5dc6c59098d712f9f3fbd1a8b438d to your computer and use it in GitHub Desktop.
Save goeko/b9b5dc6c59098d712f9f3fbd1a8b438d to your computer and use it in GitHub Desktop.

Revisions

  1. goeko created this gist Nov 26, 2024.
    72 changes: 72 additions & 0 deletions gistfile1.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,72 @@
    #!/bin/bash

    base64copy() {
    local input=""
    local output="text"
    local mimetype="text/plain"
    local base64data
    local is_text_input=0

    while [[ "$#" -gt 0 ]]; do
    case $1 in
    -o|--output)
    case "$2" in
    text|html)
    output="$2"
    shift
    ;;
    *)
    echo "Fehler: Ungültiger Ausgabe-Typ. Verwenden Sie 'text' oder 'html'."
    return 1
    ;;
    esac
    ;;
    -t|--text)
    input="$2"
    is_text_input=1
    mimetype="text/plain"
    shift
    ;;
    -h|--help)
    echo "Verwendung: base64copy [Optionen] <Datei> oder --text 'string'"
    echo "Optionen:"
    echo " -o, --output=text|html Ausgabeformat: 'text' (Standard) oder 'html' für HTML img Tag"
    echo " -t, --text=\"string\" Direkte Text-Eingabe zum Kodieren"
    echo " -h, --help Hilfe anzeigen und beenden"
    echo ""
    return 0
    ;;
    *)
    if [[ $is_text_input -eq 0 ]]; then
    input="$1"
    fi
    ;;
    esac
    shift
    done

    if [[ $is_text_input -eq 0 && ! -f "$input" ]]; then
    echo "Datei existiert nicht. Verwenden Sie --help für Informationen zur Nutzung."
    return 1
    fi

    if [[ $is_text_input -eq 0 ]]; then
    mimetype=$(file --mime-type -b "$input")
    base64data=$(base64 < "$input")
    else
    base64data=$(echo -n "$input" | base64)
    fi

    if [[ "$output" == "html" ]]; then
    echo "<img src='data:$mimetype;base64,$base64data'/>" | pbcopy
    echo "Base64-Daten mit MIME-Typ in die Zwischenablage als HTML img Tag kopiert!"
    else
    echo "data:$mimetype;base64,$base64data" | pbcopy
    echo "Base64-Daten mit MIME-Typ in die Zwischenablage als einfacher Text kopiert!"
    fi
    }

    # Nur erforderlich, wenn das Skript direkt ausgeführt wird
    if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    base64copy "$@"
    fi