I'm trying to set up a bash function that annotates the output from commands with some prefix. Currently, I have a bunch of lines of code that look like this:
git pull 2>&1 | sed "s/^/ [git pull] /"
clean_cmake_fortests 2>&1 | sed "s/^/ [cmake] /"
make -j 2 2>&1 | sed "s/^/ [make] /"
docker rmi $(docker images -a -q) 2>&1 | sed "s/^/ [docker rmi] /" | grep "removed" || true
My goal is to replace the 2>&1 | sed "s/^/$ [$1] /" bit with a function so that I can just make the above lines look something like:
git pull `annotate "git pull"`
clean_cmake_fortests `annotate "cmake"`
make -j 2 `annotate "make"`
docker rmi $(docker images -a -q) `annotate "docker rmi"` | grep "removed" || true
I defined the function annotate as
function annotate {
2>&1 | sed "s/^/ [$1] /"
}
But when executing, it has no impact, and the commands all just dump their standard output unmodified. How can I achieve what I'm intending here? I'm going for something akin to C inline macro expansions.
If anyone's curious, the point of this is to let me generate logs like this:
04: Getting proto images
[docker_get_proto_images] Fetching proto docker images...
...
[docker_get_proto_images] Status: Image is up to date for api:dev-proto
[docker_get_proto_images] ... Done.
05: Building local docker containers
[docker_local_build] [sh] Building local docker images...
[docker_local_build] [sh] NOTE: Odd behaviour may result if using outdated bases...
[docker_local_build] [sh] Local docker image build complete.
...
[docker_local_build] [sh] For advanced usage, see $ARE_TOP/deployment/docker/README
[docker_local_build]
06: Running docker-compose
[docker-compose] Starting docker_datacachedisk_1
[docker-compose] Starting docker_djangodisk_1
...
rather than this:
04: Getting proto images Fetching proto docker images... ... Status: Image is up to date for api:dev-proto ... Done. 05: Building local docker containers [sh] Building local docker images... [sh] NOTE: Odd behaviour may result if using outdated bases... [sh] Local docker image build complete. ... [sh] For advanced usage, see $ARE_TOP/deployment/docker/README 06: Running docker-compose Starting docker_datacachedisk_1 Starting docker_djangodisk_1 ...
Which gets hard to read after a while.
annotate $(git pull) "git pull". The way your syntax is written, it would enablegit pullto work on the output ofannotaterather than the other way, since arguments are evaluated before the main commandannotateis substituted after the command line has been parsed. Anything it outputs is passed to the original command as string arguments, not parsed as shell syntax.