Linux – How to include all files from a directory in shell script (/etc/init.d/iptables in this case)

bashiptableslinuxshellunix

I have an /etc/init.d/iptables start|stop|restart script on different ubuntu servers (which is a normal shell script)

For each new service I have to edit and insert a line to open a port. This leads to many different versions of the init.d script on different machines.

Is it possible to automatically include let's say all files in /etc/iptables/include.d/ ?

The target is that there should only a line in the start function of /etc/init.d/iptables like

include /etc/iptables/include.d/*

And after an additional file in /etc/iptables/include.d/ I'd simply say

/etc/init.d/iptables restart

Edit: As Saurabh pointed out this can lead to problems when commands need a certain order. An advanced setup could have different directories like:

/etc/iptables/include01.d/
/etc/iptables/include02.d/
/etc/iptables/include03.d/

and including them like this:

    include /etc/iptables/include01.d/*
    ... maybe some code goes here in the main file...
    include /etc/iptables/include02.d/*
    include /etc/iptables/include03.d/*

Best Answer

Add the following line to your init.d script.

run-parts --report /etc/iptables/include.d

It will run everything in the directory as a shell script (need to be executable).

If you you only want to execute files that ends with .port you could use something like:

run-parts --regex '\.port$' /etc/iptables/include.d/

If you want to make sure the order is correct you can name the files:

10_web.port
20_ssh.port
etc..