列出shell脚本使用的所有文件

时间:2018-05-31 13:59:16

标签: unix scripting

我有一个ksh脚本,它调用许多其他脚本。这些脚本还具有指向更多脚本的执行语句,并使用更多的配置文件。如果所有这些脚本和配置文件不在同一文件夹中,那么如何找到执行主脚本时执行的每个脚本的名称和位置以及使用的配置文件?

1 个答案:

答案 0 :(得分:0)

您可以使用strace实用程序跟踪进程及其子进程的系统调用。

例如,给定这个简单的脚本可以访问同一目录中的文件和系统上其他位置的文件:

$ cat strace-test.sh
#!/bin/sh
cat local-file.txt > /dev/null
cat /etc/issue > /dev/null

这是执行该脚本时运行strace的输出:

$ strace -q -f -t -e trace=openat bash strace-test.sh
01:42:10 openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
01:42:10 openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libtinfo.so.6", O_RDONLY|O_CLOEXEC) = 3
01:42:10 openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libdl.so.2", O_RDONLY|O_CLOEXEC) = 3
01:42:10 openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
01:42:10 openat(AT_FDCWD, "/dev/tty", O_RDWR|O_NONBLOCK) = 3
01:42:10 openat(AT_FDCWD, "/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
01:42:10 openat(AT_FDCWD, "/usr/lib/x86_64-linux-gnu/gconv/gconv-modules.cache", O_RDONLY) = 3
01:42:10 openat(AT_FDCWD, "strace-test.sh", O_RDONLY) = 3
[pid 24729] 01:42:10 openat(AT_FDCWD, "/dev/null", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
[pid 24729] 01:42:10 openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
[pid 24729] 01:42:10 openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
[pid 24729] 01:42:10 openat(AT_FDCWD, "/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
[pid 24729] 01:42:10 openat(AT_FDCWD, "local-file.txt", O_RDONLY) = 3
[pid 24729] 01:42:10 +++ exited with 0 +++
01:42:10 --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=24729, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---
[pid 24730] 01:42:10 openat(AT_FDCWD, "/dev/null", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
[pid 24730] 01:42:10 openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3
[pid 24730] 01:42:10 openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3
[pid 24730] 01:42:10 openat(AT_FDCWD, "/usr/lib/locale/locale-archive", O_RDONLY|O_CLOEXEC) = 3
[pid 24730] 01:42:10 openat(AT_FDCWD, "/etc/issue", O_RDONLY) = 3
[pid 24730] 01:42:10 +++ exited with 0 +++
01:42:10 --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=24730, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---
01:42:10 +++ exited with 0 +++

在该输出中有两行记录了预期的文件访问:

...
[pid 24729] 01:42:10 openat(AT_FDCWD, "local-file.txt", O_RDONLY) = 3
...
[pid 24730] 01:42:10 openat(AT_FDCWD, "/etc/issue", O_RDONLY) = 3
...

当然,在实际工作的真实脚本中,您将获得更多输出。这就是grep来帮助搜索它的地方。

$ sh -c "strace -q -f -t -e trace=openat bash strace-test.sh" 2>&1 \
  | grep openat \  # only match lines that include "openat"
  | grep -v -E '(.so|/usr/lib|/dev)'  # exclude lines that match 
                                      # "uninteresting" files
[pid 22711] 15:02:35 openat(AT_FDCWD, "local-file.txt", O_RDONLY) = 3
[pid 22712] 15:02:35 openat(AT_FDCWD, "/etc/issue", O_RDONLY) = 3