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
To add to others' implementations, this is my basic script boilerplate, including argument parsing (which is important if you're toggling verbosity levels).
Later...
Note: This will not cover piped commands; you need to bash -c those sorts of things, or break them up into intermediate variables or files.
It's possible to use bash's
printf
in conjunction with the%q
format specifier to escape the arguments so that spaces are preserved:Two useful shell options that can be added to the
bash
command line or via theset
command in a script or interactive session:You could make your own function to
echo
commands before callingeval
.Bash also has a debugging feature. Once you
set -x
bash will display each command before executing it.For extra timestamps and I/O info, consider the
annotate-output
command from Debian's devscripts package:Output:
Now look for a file that doesn't exist, and note the E: for STDERR output:
Output:
To answer the second part of your question, here's a shell function that does what you want:
I use something similar to this:
which prints
$
in front of the command (it looks like a shell prompt and makes it clearer that it's a command). I sometimes use this in scripts when I want to show some (but not all) of the commands it's executing.As others have mentioned, it does lose quotation marks:
but I don't think there's any good way to avoid that; the shell strips quotation marks before
echo_and_run
gets a chance to see them. You could write a script that would check for arguments containing spaces and other shell metacharacters and add quotation marks as needed (which still wouldn't necessarily match the quotation marks you actually typed).