Gerardo Navarro Suarez
Gerardo Navarro Suarez

Reputation: 423

Bash script print commands, but do not print echo command

I would like to write a bash script the prints the commands. But for readability purposes, I do not want it to print the echo commands. Unfortunately, I cannot find the correct settings for my bash script to achieve this. I need help?

#!/bin/bash

# Makes the bash script to print out every command before it is executed
set -v

echo "Cleaning test database"
RAILS_ENV=test bundle exec rake db:drop
echo "************************************************************"
echo ""

echo "Setting up the test database"
RAILS_ENV=test bundle exec rake db:setup
echo "************************************************************"
echo ""

The output looks like:

echo "Cleaning test database"
Cleaning test database
RAILS_ENV=test bundle exec rake db:drop
echo "************************************************************"
************************************************************
echo ""


echo "Setting up the test database"
Setting up the test database
RAILS_ENV=test bundle exec rake db:setup

As you can see it prints out all the commands including the echo command, which I do not want to see.

Upvotes: 15

Views: 20570

Answers (2)

Noam Manos
Noam Manos

Reputation: 16971

Thanks @123 !

To filter multiple strings from the DEBUG trap (not just echo commands), we can use regexp match too.

For example, to filter out any command that starts with "echo" or "read" or "if", I use:

trap '! [[ "$BASH_COMMAND" =~ ^(echo|read|if) ]] && echo $PS4$BASH_COMMAND' DEBUG

Update:

In order to show bash ${variable} values expended, I now use:

trap '! [[ "$BASH_COMMAND" =~ ^(echo|read|if) ]] && \
cmd=`eval echo "$BASH_COMMAND" 2>/dev/null` && echo "$cmd"' DEBUG

Upvotes: 6

123
123

Reputation: 11216

You could use trap DEBUG instead of set -v as one option.

For example

#!/bin/bash


# Makes the bash script to print out every command before it is executed except echo
trap '[[ $BASH_COMMAND != echo* ]] && echo $BASH_COMMAND' DEBUG

echo "Cleaning test database"
RAILS_ENV=test bundle exec rake db:drop
echo "************************************************************"
echo ""

echo "Setting up the test database"
RAILS_ENV=test bundle exec rake db:setup
echo "************************************************************"
echo ""

Debug is executed after every command.
$BASH_COMMAND is currently running command.

BASH_COMMAND The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap.

So the trap just checks if the last command did not start with echo and prints it.

Upvotes: 18

Related Questions