Show commands without executing them

后端 未结 4 682
太阳男子
太阳男子 2020-12-08 19:55

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          


        
相关标签:
4条回答
  • 2020-12-08 20:03

    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).

    0 讨论(0)
  • 2020-12-08 20:03

    There is a github package called maybe, here's an example:

    $ maybe rm file
    > maybe has prevented rm file from performing 1 file system operations:
    >
    > delete /home/user/file
    >
    > Do you want to rerun rm file and permit these operations? [y/N]
    
    0 讨论(0)
  • 2020-12-08 20:10

    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) the complex_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.

    0 讨论(0)
  • 2020-12-08 20:19

    Actually you can do this in a script

    add:

    set -x 
    set -n
    

    in the beginning of the script

    0 讨论(0)
提交回复
热议问题