【问题标题】:Bash "file --mime-type" command is not working in Perl ScriptBash“file --mime-type”命令在 Perl 脚本中不起作用
【发布时间】:2020-08-10 00:56:55
【问题描述】:

我正在尝试在 Perl 脚本中运行 bash 命令。我正在使用system("file --mime-type $fileName);,但在其他命令(例如ls or pwd)工作时它不起作用。 在终端中,它显示“无法打开'Paper(文件名)'(没有这样的文件或目录)。 以下是我的代码:-

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);
    }

请看终端报错截图:

我想知道为什么这不像其他命令那样工作?当我仅在终端中键入此命令时,它会正确显示文件类型,但不会在 Perl 脚本中显示。 一些帮助将不胜感激。

【问题讨论】:

    标签: linux bash perl command


    【解决方案1】:

    $filename 只是文件名,不包括目录部分。所以file 正在你的工作目录中寻找文件,而不是$a 中的目录。

    您需要连接目录名和文件名以获得完整的路径名。此外,您应该给system() 提供一个参数列表,因为您没有使用shell 解析。

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

    【讨论】:

    • 感谢您的回答和编辑。您能否也告诉我如何将它与反引号一起使用?我可能需要将其存储在标量中。此外,为什么我们需要使用'$a'?谢谢!
    • 我解释了为什么我们需要使用$a。你还指望file 知道文件在哪个目录?
    • 请参阅docstore.mik.ua/orelly/perl4/cook/ch19_06.htm,了解如何将反引号转换为不使用 shell 解析的安全代码。
    猜你喜欢
    • 1970-01-01
    • 2014-05-23
    • 2023-02-05
    • 2021-04-24
    • 2013-12-04
    • 2018-02-20
    • 2015-11-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多