Issue
I often interactively loop over e.g. my files and want to perform a specific operation on all of them, let's say I'd like to rename all files:
for file in $(ls); do mv "$file" "${file}_new"; done
This works fine. But before invoking this command, I'd like to see what it actually does, so I would add an echo in front
for file in $(ls); do echo mv "$file" "${file}_new"; done
it then shows me all the commands it would invoke. If I'm happy with them, I remove the echo
and execute it.
However, when the commands are a bit more subtle maybe including pipes or more than one command, this doesn't work anymore. Of course I could use '
so the special characters don't get interpreted, but then I don't have parameter expansion. I could also escape the special characters, but this would get very tedious.
My question is, what's the best way to do this? I've read in man bash
about the option -n
, which does "Read commands but do not execute them. This may be used to check a shell script for syntax errors. This is ignored by interactive shells." This is exactly what I need, but I need it for an interactive shell. Note that the options -x
or -v
do not help, as it will not only show the command, but also invoke it and then it might be too late already.
Solution
This thread would tell you why the option to show commands instead of executing those (a.k.a dry run) would never be implemented for bash
.
Refer to the response from Eric Blake:
>
My question is why can't such an option or be provided,A little thought would show why this will never be implemented. What would such an option output for the following:
if complex_command; then foo=command1 else foo=command2 fi $foo args
On the line for
$foo args
, there is no way to know what$foo
expands to unless you have previously executed (not just scanned) thecomplex_command
. Therefore, there is no way to dry run what the final results will be without running things, but running things is counter to the goal of a dry run.That said, you might be interested in the
bashdb
project, which uses bash hooks to provide a debugger interface where you can single-step through a bash script; it's not the same as telling you what the script would do, but it at least lets you control how much or little of the script is actually run.
Answered By - devnull Answer Checked By - Robin (WPSolving Admin)