【问题标题】:Script that calls another script to execute on every file in a directory调用另一个脚本对目录中的每个文件执行的脚本
【发布时间】:2018-02-28 18:57:22
【问题描述】:

有两个目录包含这些文件:

第一个 /usr/local/nagios/etc/hosts

[root@localhost hosts]$  ll
total 12
-rw-rw-r-- 1 apache nagios 1236 Feb  7 10:10 10.80.12.53.cfg
-rw-rw-r-- 1 apache nagios 1064 Feb 27 22:47 10.80.12.62.cfg
-rw-rw-r-- 1 apache nagios 1063 Feb 22 12:02 localhost.cfg

第二个 /usr/local/nagios/etc/services

[root@localhost services]$  ll
total 20
-rw-rw-r-- 1 apache nagios 2183 Feb 27 22:48 10.80.12.62.cfg
-rw-rw-r-- 1 apache nagios 1339 Feb 13 10:47 Check usage _etc.cfg
-rw-rw-r-- 1 apache nagios 7874 Feb 22 11:59 localhost.cfg

我有一个脚本,它遍历 Hosts 目录中的文件,并将该文件中的一些行粘贴到 Services 目录中的文件中。

脚本是这样运行的:

./nagios-contacts.sh /usr/local/nagios/etc/hosts/10.80.12.62.cfg /usr/local/nagios/etc/services/10.80.12.62.cfg

如何实现另一个脚本调用我的脚本并遍历 Hosts 目录中的每个文件并为 Service 目录中的同名文件执行其工作?

在我的脚本中,我从 Hosts 目录中的 10.80.12.62.cfg 中提取联系人,并将它们附加到 Service 目录中的同名文件中。

【问题讨论】:

  • 你试过....一个循环吗?

标签: linux bash scripting


【解决方案1】:

不要使用ls 输出作为for loop 的输入,而是使用内置通配符。请参阅 why 这不是一个好主意。

for f in /usr/local/nagios/etc/hosts/*.cfg
do
  basef=$(basename "$f")
  ./nagios-contacts.sh "$f" "/usr/local/nagios/etc/services/${basef}"
done

【讨论】:

    【解决方案2】:

    听起来你只需要做一些迭代。

    echo $(pwd)
    for file in $(ls); do ./nagious-contacts.sh $file; done;
    

    所以它会遍历当前目录中的所有文件。

    你也可以通过做一些更绝对的事情来修改它。

    abspath=$1
    for file in $(ls $abspath); do ./nagious-contacts.sh $abspath/$file; done
    

    这将遍历设置目录中的所有文件,然后将 abspath/filename 传递到您的脚本中。

    【讨论】:

    • 我可以试试,但它会将同名文件从一个目录匹配到另一个目录吗?对于Hosts目录下的10.80.12.62.cfg,脚本必须在服务目录下的10.80.12.62.cfg上执行。 ://
    • 尽量避免在for loop中使用ls输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多