简体   繁体   English

Linux Perl-一个打印其脚本名称的脚本?

[英]Linux Perl - A Script printing its script name?

I am running a script named statusCron.pl . 我正在运行一个名为statusCron.pl的脚本。

I want when I run that script, that script can detect/print its name which is statusCron.pl . 我想要在运行该脚本时,该脚本可以检测/打印其名称,即statusCron.pl By that I can detect its process ID so that if it found itself already running on the background it will kill itself. 这样,我可以检测到它的进程ID,以便如果发现它已经在后台运行,它将杀死自己。

By this I can eliminate hardcoding and re-apply it to all of my scripts. 这样,我可以消除硬编码,并将其重新应用到所有脚本中。

Additional : I dont want the directory to be included. 其他 :我不希望包含该目录。

You can use File::Basename like this: 您可以像这样使用File :: Basename:

use File::Basename;
print basename(__FILE__), "\n";

You can get the name of running program in $0 variable and to avoid the directory name we use the module File::Basename to get only the basename. 您可以在$0变量中获取正在运行的程序的名称,为避免使用目录名,我们使用模块File :: Basename仅获取基本名。

    use File::Basename;
    my $name = basename($0);
    print $name;

man perlvar for other special variables man perlvar用于其他特殊变量

您可以通过编写以下命令来打印Perl脚本文件的名称和进程ID

printf("%s %d\n", $0 =~ m|([^\\/]+)$|, $$);
#!/usr/bin/perl
print $0;

$0 stores the name of the script $0存储脚本名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM