【问题标题】:how to create a script from a perl script which will use bash features to copy a directory structure如何从 perl 脚本创建一个脚本,该脚本将使用 bash 功能来复制目录结构
【发布时间】:2013-06-01 15:04:10
【问题描述】:

嗨,我编写了一个 perl 脚本,它将所有整个目录结构从源复制到目标,然后我必须从 perl 脚本创建一个恢复脚本,这将撤消 perl 脚本所做的创建脚本(shell ) 它可以使用 bash 功能将内容从目标恢复到源我努力寻找可以递归复制的正确函数或命令(不是必需的),但我想要与以前完全相同的结构

下面是我尝试创建一个名为 restore 的文件来执行恢复过程的方式 我特别想找算法。

如果没有提供的话,restore 也会将结构恢复到命令行目录输入 你可以假设提供给 perl 脚本的默认输入 $源 $目标 在这种情况下,我们希望从目标复制到源

所以我们在一个脚本中有两个不同的部分。

1 将从源复制到目标。

2 它将创建一个脚本文件,该文件将撤消第 1 部分所做的操作 我希望这很清楚

 unless(open FILE, '>'."$source/$file") 
 {

    # Die with error message 
    # if we can't open it.
    die "\nUnable to create $file\n";
  }

    # Write some text to the file.

    print FILE "#!/bin/sh\n";
    print FILE "$1=$target;\n";
    print FILE "cp -r \n";

    # close the file.
     close FILE;

    # here we change the permissions of the file
      chmod 0755, "$source/$file";

我遇到的最后一个问题是我无法在我的还原文件中获得 $1,因为它引用了 perl 中的某个变量

但是当我运行 restore as $0 = ./restore $1=/home/xubuntu/User 时,我需要这个来获取命令行输入

【问题讨论】:

标签: perl


【解决方案1】:

首先,Perl 中执行此操作的标准方法:

 unless(open FILE, '>'."$source/$file") {
    die "\nUnable to create $file\n";
 }

就是使用or声明:

open my $file_fh, ">", "$source/$file" 
    or die "Unable to create "$file"";

这更容易理解。

更现代的方法是use autodie;,它将在打开或写入文件时处理所有 IO 问题。

use strict;
use warnings;
use autodie;

open my $file_fh, '>', "$source/$file";

您应该查看用于复制文件和目录的 Perl 模块 File::FindFile::BasenameFile::Copy

use File::Find;
use File::Basename;

my @file_list;
find ( sub {
          return unless -f;
          push @file_list, $File::Find::name;
     },
 $directory );

现在,@file_list 将包含$directory 中的所有文件。

for my $file ( @file_list ) {
    my $directory = dirname $file;
    mkdir $directory unless -d $directory;
    copy $file, ...;
}

请注意,如果mkdircopy 命令失败,autodie 也会终止您的程序。

我没有填写copy 命令,因为您要复制的位置和方式可能不同。此外,您可能更喜欢use File::Copy qw(cp);,然后在您的程序中使用cp 而不是copycopy 命令将创建一个具有默认权限的文件,而cp 命令将复制权限。

你没有解释为什么你想要一个 bash shell 命令。我怀疑您想将它用于目录副本,但无论如何您都可以在 Perl 中执行此操作。如果您仍然需要创建一个 shell 脚本,最简单的方法是通过:

print {$file_fh} << END_OF_SHELL_SCRIPT;
Your shell script goes here
and it can contain as many lines as you need.
Since there are no quotes around `END_OF_SHELL_SCRIPT`,
Perl variables will be interpolated
This is the last line. The END_OF_SHELL_SCRIPT marks the end
END_OF_SHELL_SCRIPT

close $file_fh;

请参阅 Perldoc 中的 Here-docs

【讨论】:

    【解决方案2】:

    首先,我看到您想制作一个复制脚本 - 因为如果您只需要复制文件,您可以使用:

    system("cp -r /sourcepath /targetpath");
    

    其次,如果需要复制子文件夹,可以使用-r开关,不是吗?

    【讨论】:

      猜你喜欢
      • 2017-01-26
      • 1970-01-01
      • 2012-09-20
      • 2012-07-23
      • 2014-06-05
      • 2020-05-20
      • 1970-01-01
      • 1970-01-01
      • 2016-08-05
      相关资源
      最近更新 更多