Perl调用shell命令方法小结(system/反引号/exec)

时间:2022-03-15 21:46:33

system

perl也可以用system调用shell的命令,它和awk的system一样,返回值也是它调用的命令的退出状态.

[root@AX3sp2 ~]# cat aa.pl
#! /usr/bin/perl -w
$file = "wt.pl";
system("ls -l wt.pl");
$result = system "ls -l $file";
print "$result \n"; #输出命令的退出状态
system "date";

[root@AX3sp2 ~]# perl aa.pl
-rwxr-xr-x 1 root root 126 12-16 15:12 wt.pl
-rwxr-xr-x 1 root root 126 12-16 15:12 wt.pl
0
20101216日 星期四 15:58:34 CST     

反引号

perl的system函数和awk的一样不能够返回命令的输出.
要得到命令的输出,就得使用和shell本身一样的命令: ` `

[root@AX3sp2 ~]# cat bb.pl
#! /usr/bin/perl
print `date`;
print "this is test \n";

[root@AX3sp2 ~]# perl bb.pl
20101216日 星期四 15:51:59 CST
this is test

exec

最后,perl还可以使用exec来调用shell的命令. exec和system差不多,不同之处在于,调用exec之后,perl马上就退出,而不会去继续执行剩下的代码

[root@AX3sp2 ~]# cat cc.pl
#! /usr/bin/perl
exec ("echo this is test");
print "good bye !\n";  #这句话不会被输出

[root@AX3sp2 ~]# perl cc.pl
this is test

为避免shell命令的特殊符号,采用先变量定义的方法

qilei@AFAAW-704030720:~$ cat simple.pl
#!/usr/bin/perl
use strict;
use warnings;

my $shellcmd="cat test.txt";
print `$shellcmd`;

qilei@AFAAW-704030720:~$ ./simple.pl  test.txt
a11111
a22222
a33333
a44444
a55555
a66666
a77777
a88888
a99999
a00000
b11111
b22222
b33333
b44444
b55555
b66666
b77777
b88888
b99999
b00000
qilei@AFAAW-704030720:~$