Added cmdcopy terminal output copy shortcut

This commit is contained in:
David Thurstenson 2021-05-01 17:27:43 -05:00
parent e240e96f29
commit 1210661b02
1 changed files with 71 additions and 0 deletions

71
.bashrc.d/cmdcopy.bash Normal file
View File

@ -0,0 +1,71 @@
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
final_output="$(awk -v preamble="$preamble" '{print preamble $0}' <(printf '%s\n\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"
}