Skip to content

Instantly share code, notes, and snippets.

@Mirdarthos
Last active June 20, 2024 08:59
Show Gist options
  • Save Mirdarthos/6ea065408f55fc8defce57b2673994ea to your computer and use it in GitHub Desktop.
Save Mirdarthos/6ea065408f55fc8defce57b2673994ea to your computer and use it in GitHub Desktop.
Terminal output copier
#!/usr/bin/bash
# This copies the complete output of a command piped to it, or a complete file
# including unprintable characters, making it nice for copying terminal output
# for use elsewhere, like a on Discord Forum in-between "```" tags, or HTML
# "<pre></pre>" tags.
#
# Installation instructions:
# 1. Just copy it anywhere you like. For exaample, I'm using /usr/local/bin/
# so that it's easier sysstem-wide, should it be necessary for acecess by
# more than one user. If not, you can copy it anywhere.
#
# 2. Now you need to source the file. I use ZSH so mine is sourced in
# $HOME/.zshrc but yours may vary. Because I usee ZSH, I couldn't test it
# in another environment so am not sure it would work elsewhere, but
# I suspect it'll work fine in bash as well. To source the script, run the
# following:
# echo "[[ -f <fileLocation>/tcp.sh ]] && source <fileLocation>/tcp.sh" >> <configFile>
# Where:
# * <fileLocation> is the directory containing the tcp.sh file,
# for example /usr/local/bin/; and
# * <configFile> is your shells config file. Since I use ZSH, mine is
# ~/.zshrc, but yours may vary.
# 3. Re-login to your computer or just source the .zshrc or .bashrc, or open a new terminal
# which will do it for you. It should now be usable, either by:
# * Piping the output directly to it:
# <command> | tcp
# * or, if it's a file you wish to copy:
# tcp <path/to/file.txt>
#
# Note that this is per-user and not global.
# Also note that it has only been tested on plain text files.
# Lastly note that this was originally developed for x11, it turrned out it worked on Wayland
# due to XWayland, If I'm correct. Wayland support was added at a later time, so might still be buggy.
tcp() {
if [ "$#" -gt "0" ]; then
# process args on command line
if [ -f "$1" ]; then
TXTTOCOPY=$(cat "${1}")
fi
else
# no argument, so must be must be from stdin (piped)
if input=$(cat); then
TXTTOCOPY=$(printf '%s' "${input}")
fi
fi
if [[ "${XDG_SESSION_TYPE}" == "wayland" ]]; then
if wl-copy <<< "${TXTTOCOPY}";
then
echo "Sucessfully copied the below text to the clipboard:"
echo
echo "${TXTTOCOPY}"
fi
else
if xsel --clipboard <<< "${TXTTOCOPY}";
then
echo "Sucessfully copied the below text to the clipboard:"
echo
echo "${TXTTOCOPY}"
fi
fi
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment