Leon S. Kennedy
Leon S. Kennedy

Reputation: 79

Bash "file --mime-type" command is not working in Perl Script

I am trying to run bash commands inside Perl script. I am using system("file --mime-type $fileName); but it is not working while other commands are working such as ls or pwd. In the terminal, it says "Cannot open 'Paper(filename)' (No such file or directory). Below is my code:-

foreach my $a(@ARGV)
    {
        opendir(DIR, $a) or die "You've Passed Invalid Directory as Arguments or $!\n";

        while(my $fileName = readdir DIR)
        {
            next if $fileName =~ /^\./; #this is to remove dotted hidden files.

            system("file --mime-type $fileName");

            print $fileName,"\n";
        }

        closedir(DIR);
    }

Please see the screenshot of error message in terminal:

Error Message: Cannot Open 'Paper' file.

I am wondering why is this not working like other commands? When I type this command solely in terminal then it shows the file type correctly but not in the Perl script. Some help will be highly appreciated.

Upvotes: 1

Views: 421

Answers (1)

Barmar
Barmar

Reputation: 781824

$filename is just the filename, it doesn't include the directory portion. So file is looking for the file in your working directory, not the directory in $a.

You need to concatenate the directory name and filename to get a full pathname. Also, you should give a list of arguments to system(), since you're not using shell parsing.

system('file',  '--mime-type', "$a/$fileName");

Upvotes: 3

Related Questions