使用变量在perl / bash中存储命令行

时间:2015-05-27 22:29:36

标签: perl shell

我正在尝试编写一个脚本(混合使用perl和bash)来解压缩文件。

unzip命令是特定于用户的(取决于文件),因此用户需要输入命令的开头,然后将其存储在名为$ unzipCommand(perl)的变量中。例如,用户可以输入'gunzip'或'gunzip'。例如:

MPI_Bcast(B[0], N*N, MPI_DOUBLE, ...);

此变量可以访问并且有效,例如,我可以将其打印到屏幕上。但是,我想使用它来构建一个存储在.sh文件中的命令行。

我已尝试过各种方法来做到这一点,但似乎没有任何效果。 Tha变量看起来像这样:

my $unzipCommand = "gunzip";

为了将它存储在shell脚本中,我尝试过:

my $cmd = "$unzipCommand $path2zippedfile > $path2file";

`echo "$cmd" > $sh_script`;

命令似乎总是“执行”而不是打印在文件中。

我知道该命令有效,因为如果我硬编码'gunzip',我就不会收到此错误。

非常感谢任何帮助。 谢谢!

3 个答案:

答案 0 :(得分:1)

您可以尝试使用此代码。

open ('FH','>',$sh) or die "unable to open $!\n";
my @arr = split(/' '/,$cmd);
foreach(@arr){ print FH $_;}
close(FH);

我假设$sh是脚本名称,而$cmd是您要在脚本中编写的命令。

答案 1 :(得分:0)

尝试以下

open (FH, ">", "$sh_Script") or die "Can't open File Handle";
print FH "$cmd";
close FH;

我假设$sh_Script是您想要的脚本路径,$cmd是您要存储在文件中的内容。

答案 2 :(得分:0)

我的贡献(完整脚本),它采用硬编码值并使用单行创建一个小shell脚本。

#!/usr/bin/perl

use strict;

my $unzipCommand = "gunzip";
my $path2zippedfile = "/home/honnor/zip1.gz";
my $unzipperScript = "unzipper.ksh";
my $cmd = "$unzipCommand $path2zippedfile";

print "$cmd";


open( my $fh, ">", $unzipperScript ) or die $!;
print $fh "$cmd";
close $fh;
相关问题