Last active
April 6, 2022 02:52
-
-
Save wojas/c4e33eccec2da0a375f9523f60ab92d0 to your computer and use it in GitHub Desktop.
Prefix shell command output with a colored string (supports stderr)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
raw_prefix="$1" | |
prefix_width=${PREFIX_WIDTH:-20} | |
color=color_${PREFIX_COLOR:-green} | |
error_color=color_${PREFIX_ERROR_COLOR:-red} | |
shift 1 | |
if [ "$raw_prefix" = "" ]; then | |
echo "USAGE: $0 <prefix> <command> [args..]" | |
echo | |
echo "If prefix is '-', then the command itself will be used as prefix." | |
echo | |
echo "Environment vars:" | |
echo " PREFIX_WIDTH - formatted width of prefix (default 20, you can use 0)" | |
echo " PREFIX_COLOR - one of: black red green yellow blue purple cyan white none (default: green)" | |
echo " PREFIX_ERROR_COLOR - color used for stderr (default: red)" | |
echo | |
echo "Advanced examples:" | |
echo ' seq 12 | parallel prefix - echo "input was {}"' | |
echo ' echo -n http://example.com/a.txt http://example.com/b.txt | parallel -d ' ' prefix {} wget {}' | |
exit 1 | |
fi | |
if [ "$raw_prefix" = "-" ]; then | |
raw_prefix="$*" | |
fi | |
color_reset='\x1B[0m' # Text Reset | |
color_black='\x1B[1;30m'; | |
color_red='\x1B[1;31m'; | |
color_green='\x1B[1;32m'; | |
color_yellow='\x1B[1;33m'; | |
color_blue='\x1B[1;34m'; | |
color_purple='\x1B[1;35m'; | |
color_cyan='\x1B[1;36m'; | |
color_white='\x1B[1;37m'; | |
if [ "$color" = "color_none" ]; then | |
c="" | |
r="" | |
else | |
c=${!color} | |
r=$color_reset | |
fi | |
if [ "$error_color" = "color_none" ]; then | |
ec="" | |
er="" | |
else | |
ec=${!error_color} | |
er=$color_reset | |
fi | |
prefix=`printf "$c%-${prefix_width}s|$r" "$raw_prefix" | sed -e 's/[\\/&]/\\\\&/g'` | |
error_prefix=`printf "$ec%-${prefix_width}s*$er" "$raw_prefix" | sed -e 's/[\\/&]/\\\\&/g'` | |
"$@" 2> >(sed "s/^/$error_prefix /g" > /dev/stderr) > >(sed "s/^/$prefix /g") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment