Ubuntu – Display output of command executed in bash as it is executing

bashscripts

I've got a line in my bash script like this:

echo "`some_command`"

Now, some_command executes for around 1-2mins and it keeps printing alerts/messages in that interval.

Problem is when I execute my bash script, the script has no output for 1-2mins and then directly displays the output after complete execution of some_command.

How can I make my bash script output some_command as it is executing? Is there a way to do so?

Best Answer

xtrace

You could set the xtrace option (commonly used for debugging shell scripts) before running the command (no need to use command substitution). Also, don’t forget to unset the option afterwards.

set -x
some_command
set +x

Example:

$ set -x; sleep 2 && echo fin; set +x
+ sleep 2
+ echo fin
fin
+ set +x

echo

If you find the xtrace output to be too cluttered, you could simply echo the name of the command beforehand:

echo some_command
some_command
Related Question