Hi everyone, This is the first time I posting question here. Please be nice to me. I'm not a very experience Linux user so I really need some help here because of my limited knowledge to Linux.
I want to write a script to change few setting in few configuration files in RHEL 6 and 7. Below are some of the thing i want to archive:
1. Make a copy for all the files that will be modify by the script with format file.DDMMYYYY. If found a backup exist then ignore. Cause I done some testing and found out that if the scripts executed more than once in the same date, then the backup file will be the one that have made changes of.
2. The script will find certain parameter in a file and change the value if found. If not found then add the parameter in.
3. If the file is not found, then create the file and put the parameters in the file. Set permission for it as well.
Below is the noob script I have done, I know there are a lot of improvement with the script. The script is just an example of what needed to archive. Hope there will be nice guys willing to share their knowledge with me.
Code:
#!/bin/bash
###backup file###Please guide me how to ignore if the backup file already exist.###
cp -Rp /home/admin/Documents/1_file /home/admin/Documents/1_file.$(date +"%d%h%Y")
cp -Rp /home/admin/Documents/CIS.conf /home/admin/Documents/CIS.conf.$(date +"%d%h%Y")
cp -Rp /home/admin/Documents/2_file.conf /home/admin/Documents/2_file.conf.$(date +"%d%h%Y")
###Add line to the file###
echo "i successful add line to the file" > /home/admin/Documents/1_file
###Append line to the file###
echo "find and replace=not success" >> /home/admin/Documents/1_file
###Find word and replace###
sed -i 's/i successful add line to the file/admin successful add line to the file/' /home/admin/Documents/1_file
###Find line and replace###Problem facing here is the "=" might have space or non space, how do i find the setting and replace whatever after with a value?###
sed -i 's/find and replace=not success/find and replace=success/' /home/admin/Documents/1_file
###Create file and add text to it###How to check if the file not exist, then only create?###
touch notfound.conf
cat<<END>notfound.conf
Line1
Line2
Line3
Line4
Line5
END
###Find parameter in a file and replace the value###
sed -i "s/Line4/Line5/" notfound.conf
sed -i "s/Line2/Line4/" notfound.conf
###Change permission and owner###
chmod 644 notfound.conf
chown admin:admin notfound.conf
###Find parameter with hashtag and unhastag them/vice versa, change the value also###Same issue with previous one, the output is the word will be insert in between which have two = ####
sed -i "r/#Try unhashtag me*/Try unhashtag me = success/" /home/admin/Documents/2_file.conf
sed -i 's/Try hashtag/#Try hashtag* = sucess/' /home/admin/Documents/2_file.conf