mjs mjs - 1 year ago 45
Bash Question

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


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
that will output a command and then run it?

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

mjs mjs

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