in reply to Unix command working with Perl

check out the docs for system. use the multiple argument form, and check the return code. also, use taint mode to check the arguments for nasty surprises. the following code is untested...

Update: note this code applies to any system calls, not just 'mv'. there are better tools for moving files, as mentioned by other monks.

#!/usr/bin/perl -wT use strict; ## check your arguments @_ == 2 or die "Usage: $0 from to\n"; ## specify your command my $cmd = '/usr/bin/mv'; ## untaint your input my( $from ) = ( $ARGV[0] =~ s/(\w|[/\\])+/$1/ ); my( $to ) = ( $ARGV[1] =~ s/(\w|[/\\])+/$1/ ); ## make sure the input is good ( defined $from and defined $to ) or die "ERROR: $0 - bad input\n"; ## run the command without using the shell ## check return code for errors system( $cmd, $from, $to ) or die "ERROR: $0 - can't $cmd! $!";
Update: escaped backslash in regex

~Particle *accelerates*

Replies are listed 'Best First'.
Re: Re: Unix command working with Perl
by Anonymous Monk on May 31, 2002 at 14:35 UTC
    thanks for all the answers! I keep getting the following errors:
    /(\w|[/: unmatched [] in regexp at tes2 line 12.
    The other error keeps popping up reference to checking of arguments but I am running it with two arguments at command line. My script name is tes2:
    tes2 Oldfile Newfile
    Usage: tes2 from to

      Update: Ahh, this was a comment to particle's code ... now I see ... nothing to see here

      /(\w|[/: unmatched [] in regexp at tes2 line 12.
      Aehmm, what regex?? If you show us all your code we might be able to help you ...

      -- Hofmator

      the \ should have been escaped... i didn't think that was necessary in brackets. i've updated my code.

      ~Particle *accelerates*