简体   繁体   中英

Use a variable to store a command line in perl/bash

I am trying to write a script (mix of perl and bash) to unzip files.

The unzip command is user-specific (depending on files), so the user needs to enter the beginning of the command, which is then store in a variable called $unzipCommand (perl). For example, the user could enter 'gunzip' or 'gunzip'. For example:

my $unzipCommand = "gunzip";

This variable is accessible and works, for example, I can print it to the screen. However, I want to use this to build a command line that I store in a .sh file.

I have tried various ways to do this, but nothing seems to work. Tha variable looks like this:

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

And to store it in a shell script, I have tried:

`echo "$cmd" > $sh_script`;

and

open $sh_script, ">", "$QSUB" or die "Can't open '$QSUB'";
print $sh_script "$cmd";
close $sh_script;

It always seems that the command is 'executed' instead of printed in the file.

I know that the command works because if I hard code the 'gunzip', I don't get this error.

Any help would be greatly appreciated. Thanks!

You can try this code.

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

I am assuming that $sh is the script name and $cmd is the command which you want to write in script.

Try the following

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

I am assuming the $sh_Script is the path to your script which you want and $cmd is what you want to store in the file.

My contribution (full script) which takes hardcoded values and creates a little shell script with a single line.

#!/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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM