bashrc/.bashrc.d/cmdcopy.bash

72 lines
1.6 KiB
Bash
Raw Normal View History

cmdcopy() { # Terminal output copying shortcut
#
# USAGE
#
# cmdcopy [-p <preamble>] <cmd>
#
#
# DESCRIPTION
#
# Formats the output of <cmd> to include "$ <cmd>\n" on the
# first line for easy pasting. When -p is set, <preamble>
# is added to the beginning of every resulting line.
#
#
# OPTIONS
#
# -p <preamble> Add <preamble> as a string to the
# beginning of every line.
#
#
# ENVIRONMENT
#
# cmdcopy_clipprog Specify the clipboard management
# program to use. Program must
# accept content on stdin.
# Default: `wl-copy`
# Default clipboard management program
# NOTE: Must accept final output on stdin
default_clipprog="wl-copy"
# Set $clipprog to the contents of $cmdcopy_clipprog. If $cmdcopy_clipprog
# is empty or unset, set $clipprog to the contents of $default_clipprog instead.
clipprog="${cmdcopy_clipprog:-$default_clipprog}"
# Parse command line options
while getopts :p: opt; do
case $opt in
p)
preamble="$OPTARG"
;;
\?)
echo "E: Unknown option: -$OPTARG"
return 1
;;
:)
echo "E: Option -$OPTARG requires an argument"
return 1
;;
esac
done
# Remove parsed options from $@
shift $((OPTIND -1))
# Run the command, capturing stdout and stderr
cmd_output="$("$@" 2>&1)"
# Add preamble
2021-05-01 22:34:12 +00:00
final_output="$(awk -v preamble="$preamble" '{print preamble $0}' <(printf '%s\n%s' "$ $*" "$cmd_output"))"
# Send final output to $clipprog
printf '%s' "$final_output" | $clipprog
# Print command output to the terminal for user feedback
printf '%s\n\ncmdcopy: Command output sent to: %s\n\n' "$final_output" "$clipprog"
}