SaltedPork
SaltedPork

Reputation: 377

Using system command in Perl for using gzip

I have some zipped files (.gz format) and I want to automate that process.Here is what I have:

    !# /usr/bin/perl -w
    use strict;

    my $input1 = $ARGV[0];
    my $unzip_command = 'gzip -d $input1';
    system $unzip_command;

I'm getting an error that asks to use -f to force decompression (tried it, just hangs). Can you spot where my syntax went wrong?

Upvotes: 0

Views: 985

Answers (2)

PerlDuck
PerlDuck

Reputation: 5720

As already stated in this answer you have to use double quotes for the $input1 to get interpolated (expanded).

But

your script is vulnerable to code-injection. Consider this case (assuming your script's name is decompress.pl):

$ ./decompress.pl "foo.gz; rm -rf /"

This will finally execute

gzip -d foo.gz; rm -rf /

Please read about the two modes system can be called in: either with a string (which is then interpreted by your shell) or with an array of arguments (which bypasses the shell and its interpretation).

Better would be to use the array-mode here:

#!/usr/bin/perl
use strict;
use warnings;

my $input1 = $ARGV[0];
my @unzip_command = ('gzip', '-d', $input1);
system( @unzip_command );

(Btw: you had a typo in your she-bang line. It's not !#/usr/bin/perl but #!…. Please paste your code instead of re-typing it to avoid typos.)

Upvotes: 2

harmic
harmic

Reputation: 30577

Use double quotes when you want a variable to be interpolated.

my $unzip_command = "gzip -d $input1";

Otherwise you will be executing the command 'gzip -d $input1' rather than 'gzip -d myfile.gz'.

In this case, system is passing your command to the shell, which is interpreting $input1 as a shell variable. Of course that does not exist.

Upvotes: 2

Related Questions