至少在基于 Debian 的系统下,debianutils包中有一个run-parts
实用程序,可用于各种脚本。例如在 /etc/X11/Xsession.conf 中。它将运行在目录中找到的所有可执行文件。为什么需要运行部件而可以与选项或实用程序一起使用?另外,什么是可执行文件?看起来它不是简单地检查文件权限:find
-perm
test
run-parts
# run-parts --list --lsbsysinit /etc/X11/Xsession.d | tail -1
/etc/X11/Xsession.d/90x11-common_ssh-agent
# ls -l /etc/X11/Xsession.d/90x11-common_ssh-agent
-rw-r--r-- 1 root root 629 2010-11-02 23:17 /etc/X11/Xsession.d/90x11-common_ssh-agent
# head /etc/X11/Xsession.d/90x11-common_ssh-agent
# $Id: 90x11-common_ssh-agent 305 2005-07-03 18:51:43Z dnusinow $
# This file is sourced by Xsession(5), not executed.
STARTSSH=
SSHAGENT=/usr/bin/ssh-agent
SSHAGENTARGS=
if has_option use-ssh-agent; then
if [ -x "$SSHAGENT" ] && [ -z "$SSH_AUTH_SOCK" ] \
#
Run Code Online (Sandbox Code Playgroud)
您可以使用find
代替run-parts
,无法显示哪个更好。但我认为 usingrun-parts
更短(更少输入)并使您的脚本更易于维护。一个例子是/etc/crontab
:
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# m h dom mon dow user command
17 * * * * root cd / && run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
Run Code Online (Sandbox Code Playgroud)
对于第二个问题,您可以在debianutils
源代码中找到答案。在文件中run-parts.c
,第 198 行:
/* Execute a file */
void run_part(char *progname)
{
....
args[0] = progname;
execv(progname, args);
error("failed to exec %s: %s", progname, strerror(errno));
exit(1);
....
}
Run Code Online (Sandbox Code Playgroud)
你可以看到run-parts
使用execv
系统调用。因此,如果您的文件不是二进制可执行文件或Interpreter script
,execv
则无法运行该文件。
笔记
Interpreter script
:从man execve
, 部分Interpreter scripts
:
Interpreter scripts
An interpreter script is a text file that has execute permission
enabled and whose first line is of the form:
#! interpreter [optional-arg]
The interpreter must be a valid pathname for an executable which is not
itself a script. If the filename argument of execve() specifies an
interpreter script, then interpreter will be invoked with the following
arguments:
interpreter [optional-arg] filename arg...
where arg... is the series of words pointed to by the argv argument of
execve().
For portable use, optional-arg should either be absent, or be specified
as a single word (i.e., it should not contain white space); see NOTES
below.
Run Code Online (Sandbox Code Playgroud)