开发者

Why isn't this command taking the diff of two directories?

开发者 https://www.devze.com 2023-01-23 09:35 出处:网络
I am asked to diff two directories using Perl but I think something is wrong with my command, $diff = system(\"sudo diff -r \'/Volumes/$vol1\' \'/Volumes/$vol2\\\\ 1/\' >> $diff.txt\");

I am asked to diff two directories using Perl but I think something is wrong with my command,

$diff = system("sudo diff -r '/Volumes/$vol1' '/Volumes/$vol2\\ 1/' >> $diff.txt");

It does开发者_如何学Pythonn't display and output. Can someone help me with this? Thanks!


It seems that you want to store all differences in a string.

If this is the case, the command in the question is not going to work for a few reasons:

  • It's hard to tell whether it's intended or not, but the $diff variable is being used to set the filename storing the differences. Perhaps this should be diff.txt, not $diff.txt

  • The result of the diff command is saved in $diff.txt. It doesn't display anything in STDOUT. This can be remedied by omitting the >> $diff.txt part. If it also needs to be stored in file, consider the tee command:

    sudo diff -r dir1/ dir2/ | tee diff.txt
    
  • When a system call is assigned to a variable, it will return 0 upon success. To quote the documentation:

    The return value is the exit status of the program as returned by the wait call.

    This means that $diff won't store the differences, but the command exit status. A more sensible approach would be to use backticks. Doing this will allow $diff to store whatever is output to STDOUT by the command:

    my $diff = `sudo diff -r dir1/ dir2/ | tee diff.txt`;  # Not $diff.txt
    
  • Is it a must to use the sudo command? Avoid using it if even remotely possible:

    my $diff = `diff -r dir1/ dir2/ | tee diff.txt`;  # Not $diff.txt
    

A final recommendation

Let a good CPAN module take care of this task, as backtick calls can only go so far. Some have already been suggested here; it may be well worth a look.


Is sudo diff being prompted for a password? If possible, take out the sudo from the invocation of diff, and run your script with sudo.


"It doesn't display and output." -- this is becuase you are saving the differences to a file, and then (presumably) not doing anything with that resulting file.

However, I expect "diff two directories using Perl" does not mean "use system() to do it in the shell and then capture the results". Have you considered doing this in the language itself? For example, see Text::Diff. For more nuanced control over what constitutes a "difference", you can simply read in each file and craft your own algorithm to perform the comparisons and compile the similarities and differences.


You might want to check out Test::Differences for a more flexible diff implementation.

0

精彩评论

暂无评论...
验证码 换一张
取 消