如何使用 Perl 获得 bash 内置命令
我想知道是否有办法使用 perl 脚本获取 Linux 命令。我说的是诸如cd ls llclear cp
之类的命令
I was wondering if there is a way to get Linux commands with a perl script. I am talking about commands such as cd ls ll clear cp
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以通过多种方式执行系统命令,其中一些方式比其他方式更好。
system();
,打印命令的输出,但不将输出返回到 Perl 脚本。exec();
,它与system();
做同样的事情,但根本不返回到Perl脚本,除非命令不存在或失败。open();
,它允许您将输入从脚本传输到命令,或者将命令的输出读入脚本。值得一提的是,您列出的系统命令(如 cp 和 ls )使用 Perl 本身的内置函数可以更好地完成。任何系统调用都是一个缓慢的过程,因此当所需结果很简单(例如复制文件)时,请使用本机函数。
一些示例:
此页面更详细地解释了进行系统调用的不同方式。
You can execute system commands in a variety of ways, some better than others.
system();
, which prints the output of the command, but does not return the output to the Perl script.qx();
function, which is easier to read and accomplishes the same thing.exec();
, which does the same thing assystem();
, but does not return to the Perl script at all, unless the command doesn't exist or fails.open();
, which allows you to either pipe input from your script to the command, or read the output of the command into your script.It's important to mention that the system commands that you listed, like
cp
andls
are much better done using built-in functions in Perl itself. Any system call is a slow process, so use native functions when the desired result is something simple, like copying a file.Some examples:
This page explains in a bit more detail the different ways that you can make system calls.
正如 voithos 所说,您可以使用
system()
或反引号。但是,请考虑到不建议这样做,并且例如,cd
不起作用(实际上不会更改目录)。请注意,这些命令是在新 shell 中执行的,不会影响正在运行的 perl 脚本。我不会依赖这些命令并尝试在 Perl 中实现您的脚本(如果您决定使用 Perl,无论如何)。事实上,Perl 最初被设计为系统管理员的 sh 和其他 UNIX shell 的强大替代品。
You can, as voithos says, using either
system()
or backticks. However, take into account that this is not recommended, and that, for instance,cd
won't work (won't actually change the directory). Note that those commands are executed in a new shell, and won't affect the running perl script.I would not rely on those commands and try to implement your script in Perl (if you're decided to use Perl, anyway). In fact, Perl was designed at first to be a powerful substitute for sh and other UNIX shells for sysadmins.
您可以将命令放在反引号中
`命令`
you can surround the command in back ticks
`command`
问题是 perl 试图执行 bash 内置命令(即
source
,...),就好像它们是真实文件一样,但 perl 无法找到它们,因为它们不存在。答案是告诉 perl 明确执行什么。对于像source
这样的 bash 内置命令,执行以下操作即可正常工作。对于
cd
的情况,执行如下操作。The problem is perl is trying to execute the bash builtin (i.e.
source
, ...) as if they were real files, but perl can't find them as they don't exist. The answer is to tell perl what to execute explicitly. In the case of bash builtins likesource
, do the following and it works just fine.of for the case of
cd
do something like the following.