Prefix to each output of a command on runtime
I assume that what you are doing in your allcommands.sh is:
command1.sh
command2.sh
Just relace it with
command1.sh | sed "s/^/[command1] /"
command2.sh | sed "s/^/[command2] /"
A minimal example of allcommands.sh
:
#!/bin/bash
for i in command{1,2}.sh; do
./"$i" | sed 's/^/['"${i%.sh}"'] /'
done
With command1.sh
and command2.sh
executable and in the same directory just echo
ing the wanted strings, this gives the shell output:
$ ./command1.sh
file exists
file moved
$ ./command2.sh
file copied
file emptied
$ ./allcommands.sh
[command1] file exists
[command1] file moved
[command2] file copied
[command2] file emptied
Quick sed
breakdown
sed 's/^/['"${i%.sh}"'] /'
s/
enters "regexp pattern match and replace" mode^/
means "match the beginning of every line"${i%.sh}
happens in the shell context and means "$i
, but strip the suffix.sh
"['"${i%.sh}"'] /
at first prints a[
, then exits the quoted context to grab the$i
variable from the shell, then re-enters to finish with the]
and a space.