Search code examples
bashshellmakefileecho

Echo command, and then run it? (Like make)


Is there some way to get bash into a sort of verbose mode where, such that, when it's running a shell script, it echoes out the command it's going to run before running it? That is, so that it's possible to see the commands that were run (as well as their output), similar to the output of make?

That is, if running a shell script like

echo "Hello, World"

I would like the following output

echo "Hello, World"
Hello, World

Alternatively, is it possible to write a bash function called echo_and_run that will output a command and then run it?

$ echo_and_run echo "Hello, World"
echo "Hello, World"
Hello, World

Solution

  • It's possible to use bash's printf in conjunction with the %q format specifier to escape the arguments so that spaces are preserved:

    function echo_and_run {
      echo "$" "$@"
      eval $(printf '%q ' "$@") < /dev/tty
    }