Let Bash Trap DEBUG See Trumpet As One Command

I use

trap 'echo -e "\e[92m$ $BASH_COMMAND\e[0m"' DEBUG 

in a bash script to print each executed command.

This works fine except that it prints two commands when I connect them:

 bzip2 -dc < dump.sql.bz2 | mysql test 

Print

 $ bzip2 -dc < dump.sql.bz2 $ mysql test 

Can I make changes to trap or to a line with a pipe so that the line is printed as one?

+5
source share
2 answers

Change your command to:

 mysql test < <(bzip2 -dc < dump.sql.bz2) 

Using a process substitute instead of a pipeline makes the command a simple command from the Bash perspective, which is the level of detail at which the DEBUG trap and the $BASH_COMMAND built-in variable.

Background

The DEBUG signal (pseudo) by design works at the level of simple commands, like $BASH_COMMAND .

bzip2 -dc < dump.sql.bz2 | mysql test bzip2 -dc < dump.sql.bz2 | mysql test is a pipeline made up of a few simple commands.

Therefore, your trap statement cannot do what you want with the pipeline.

The immediate task is to get what you want with a compound command (for example, a while or a group of commands ( { ...; ...; } ) or a list of commands (simple commands or pipelines connected to operators ; && || & ) , - use set -v , which intercepts the entire stderr command before executing it, but I don’t know how to control the formatting of this output.

+2
source

An unexpected workaround will use a function, for example:

 run () { eval $1; } trap 'echo -e "\e[92m$ $BASH_COMMAND\e[0m"' DEBUG run "bzip2 -dc < dump.sql.bz2 | mysql test" 

Output:

 $ run "bzip2 -dc < dump.sql.bz2 | mysql test" 
+1
source

Source: https://habr.com/ru/post/1247814/


All Articles