0

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?

2 Answers 2

2

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.)

Sign up to request clarification or add additional context in comments.

1 Comment

Good point. Also fails if the filename contains any spaces or shell meta characters.
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.