0

I'm writing a small bash script where I am compiling 2 programs then executing them in the background within a bash script. These 2 programs do output some generic text. However I need to prefix these outputs like PROGRAM1: xxxxx. How do I achieve that? I have found several answers here however they weren't exactly applicable to this situation.

Here's the code:

#!/bin/bash
echo "This program compiles 2 programs, executes them (executes the 2nd one first, then sleeps for 0.01 second which then executes program 1), then observes the outputs"

gcc -O3 -std=c11 one.c -o one
gcc -O3 -std=c11 two.c -o two

./two &
sleep 0.01
TWO_PID=$(pgrep two)

./one $TWO_PID

#"Prefix output statements here"
#add code here

#Cleanup
rm -f one two

1 Answer 1

3

You can do something like this

#! /bin/bash

# ...

label() {
    while read -r l; do
        echo "$1: $l"
    done
}

./two | label "two" &
two_pid=$(pgrep two)
./one $two_pid | label "one"

You don't need the sleep and be careful as pgrep could match more than one process.

Also, instead of compiling and removing you should use make.

Sign up to request clarification or add additional context in comments.

3 Comments

I need to do the sleep as it's requirement for a practice problem I'm working on.
"Also, instead of compiling and removing you should use make." Do you mean to have a makefile in same directory and just call make within the bash script? Thanks for the answer!
Usually making and running are separate things but you can invoke make from the script if you want, at least it won't make it if sources didn't change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.