Beginner's Guide: Configuring an IP Alias with a Script
This guide is designed for users with no prior Linux experience. Follow these easy steps to
add a new IP alias using a script.
---
Step 1: Save the Script
1. Open a terminal.
2. Type the following command to create a new file:
nano ip_alias.sh
3. Copy and paste the script below into the terminal:
#!/bin/bash
# Detect interface
INTERFACE=$(ls /etc/sysconfig/network-scripts/ifcfg-* | grep -v ':0' | grep -v 'lo' | head -n
1 | sed 's#.*/ifcfg-##')
[ -z "$INTERFACE" ] && { echo "No interface found."; exit 1; }
# User inputs
read -p "IP Address: " IPADDR
read -p "Subnet Mask (e.g., 255.255.255.0): " NETMASK
read -p "Default Gateway (optional): " GATEWAY
# Create alias configuration
ALIAS="/etc/sysconfig/network-scripts/ifcfg-${INTERFACE}:0"
sudo cp /etc/sysconfig/network-scripts/ifcfg-${INTERFACE} $ALIAS
sudo sed -i "s/^DEVICE=.*/DEVICE=${INTERFACE}:0/;
s/^BOOTPROTO=.*/BOOTPROTO=Static/; s/^NAME=.*/NAME=${INTERFACE}:0/" $ALIAS
sudo sed -i "/^IPADDR=.*/d; /^NETMASK=.*/d; /^GATEWAY=.*/d" $ALIAS
echo -e "IPADDR=$IPADDR\nNETMASK=$NETMASK" | sudo tee -a $ALIAS
[ "$GATEWAY" ] && echo "GATEWAY=$GATEWAY" | sudo tee -a $ALIAS
# Restart network
sudo systemctl restart network
echo "Done. If remote, reconnect using: ssh user@$IPADDR"
4. Press `Ctrl + O`, then `Enter` to save, and `Ctrl + X` to exit.
Step 2: Make the Script Executable
Type the following command:
chmod +x ip_alias.sh
This makes the script ready to run.
Step 3: Run the Script
1. Execute the script with the command:
sudo ./ip_alias.sh
2. Follow the prompts to enter:
- IP Address: The new IP address you want to set.
- Subnet Mask: The network mask (e.g., `255.255.255.0`).
- Default Gateway: (Optional) Enter if required.
The script will automatically configure the new IP alias and restart the network service.
Step 4: Verify the New IP
1. After the script completes, type the following command to check the network settings:
ifconfig
2. Look for the new alias (e.g., `eth0:0`) and ensure the new IP address is displayed.
---
**Important:** If you are using this script over a remote connection, reconnect to the new
IP address after running it. Example:
ssh user@<new-ip-address>