How to run a startup script automatically after a network interface is up on CentOS

Last updated on October 27, 2020 by Dan Nanni

Sometimes you may want to run a specific command or a custom script right after a given network interface (e.g., eth0) is up. For example, you want to configure interface-specific iptables rules or QoS settings. Follow this guideline to learn how to set up a startup script for a specific network interface on CentOS.

On CentOS, network interface related scripts are found in /etc/sysconfig/network-scripts. Among them is ifup-post, which is called right after any network interface is brought up online. In this script, you will find the following code snippet toward the end.

#!/bin/sh
if [ -x /sbin/ifup-local ]; then
    /sbin/ifup-local ${DEVICE}

The code snippet means that if there exists a script called ifup-local in /sbin directory, the script gets executed with an interface name argument. On vanilla CentOS system, no such script exists. So in order to run a startup script automatically after a network interface is up, create an executable script /sbin/ifup-local, and put in there any command or script you want to run. For example:

$ sudo vi /sbin/ifup-local
#!/bin/sh
if [[ "$1" == "eth0" ]]
then
    echo "this part will be executed right after eth0 is up."
    echo "so you can put any startup command for eth0 here."
else
    #DO_NOTHING
fi

Finally, make the script executable.

$ sudo chmod +x /sbin/ifup-local

Support Xmodulo

This website is made possible by minimal ads and your gracious donation via PayPal (Credit Card) or Bitcoin (1M161JGAkz3oaHNvTiPFjNYkeABox8rb4g).

Please note that this article is published by Xmodulo.com under a Creative Commons Attribution-ShareAlike 3.0 Unported License. If you would like to use the whole or any part of this article, you need to cite this web page at Xmodulo.com as the original source.

Xmodulo © 2021 ‒ AboutWrite for UsFeed ‒ Powered by DigitalOcean