Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
623 views
in Technique[技术] by (71.8m points)

bash - Show commands without executing them

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no option for "dry run" as explained by devnull but there is a simple workaround:

debug=
#debug=echo

$debug mv "$file" "${file}_new"

If you remove the comment from the second assignment (without changing anything else), you enable "dry run" for the dangerous mv command.

A more elaborate approach would be to check some condition (like a command line option):

debug=
if [[ ...enable dry run?... ]]; then
    debug=echo
fi

Note: The empty assignment is only necessary when you have the option -u ("Treat unset variables as an error when substituting.") enabled.

Important: This won't work well, when your commands use redirections (because the shell will always do them before the command is even started).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...