0

I want to create a ifcfg-file in /etc/sysconfig/network-scripts/ and then create a script that reads user input and outputs it to the ifcfg-file

example lines will be like:

Onboot: Yes or No(they either input yes or no)

and then it will output it like "Onboot=Yes"

After that it will output and write it to that new ifcfg-file

It will also have just regular input like when asked to input "ipaddr"

If you can just help me get it started and then I can take it from there. All help will be greatly appreciated.

1 Answer 1

0

Here is a script to start with.
It takes the port name as input, as ifcfg files match the name of port, so if the provided port name is invalid it throws error.
Also, you can add further options to add like IPADDR, DEVICE, etc which if present in the ifcfg-file will be replaced with new value provided, else it will be appended to the file.

#!/usr/bin/bash

function usage() {
    echo "Usage:"
    echo "$0 <port-name>"
}

function input_to_file() {
    param=$1
    value=$2
    portname=$3
    ifcfgfile="/etc/sysconfig/network-scripts/ifcfg-$portname"
    echo $param=$value
    grep -q "^$param=" $ifcfgfile && sed "s/^$param=.*/$param="$2"/" -i $ifcfgfile ||
    echo $param="$value" >> $ifcfgfile
}

if [[ $# -lt 1 ]]; then
    usage;
    exit 1;
fi

portname=$1

# Validate the port-name passed
ifconfig $portname &> /dev/null
if [[ $? -ne 0 ]]; then
    echo "Invalid port name passed"
    exit 1
fi    

ifcfgfile="/etc/sysconfig/network-scripts/ifcfg-$portname";
# Create file if not present for a valid port. This is actually not required if you are creating file prior to running script.
if [ ! -f $ifcfgfile ]; then
    touch $ifcfgfile
fi

echo -n "ONBOOT=[yes/no]: ";
param="ONBOOT"
read value
input_to_file $param $value $portname

Further enhancement to this script would be to validate the inputs, like if value for ONBOOT is other than yes/no, throw error, if invalid IPADDR is passed, throw error, etc. However, I leave it to you on your requirements.

2
  • Thank you very much. I can't wait to see how this works i appreciate all the help. if i have any more questions please forgive me i am fairly new to scripting but I am very driven to learn.
    – Burritoboy
    Apr 8, 2018 at 13:33
  • @Burritoboy if this answer is helpful for you, please don't hesitate to upvote it :) May 14, 2018 at 8:04

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .