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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…