I’m writing a bash script, in the script, I want to download and install EPEL repo for CentOS, but as you can see, the repo links are difference for each OS version.
https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
https://dl.fedoraproject.org/pub/epel/epel-release-latest-8.noarch.rpm
https://dl.fedoraproject.org/pub/epel/epel-release-latest-9.noarch.rpm
So, I want to get the value of CentOS version then assign it to a variable then my script can run in any CentOS version without specify link for each version.
# cat /etc/os-release
NAME="CentOS Stream"
VERSION="8"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="8"
# cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
# cat /etc/os-release
NAME="CentOS Stream"
VERSION="9"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="9"
To achieve that goal, I use the grep command as follows:
The excludes the VERSION_ID=” and the means to keep matching until found.
grep -oP 'VERSION_ID="\K[^"]+' /etc/os-release
# grep -oP 'VERSION_ID="\K[^"]+' /etc/os-release
8
Then I assign it to the variable $os_ver.
os_ver=$(. /etc/os-release; echo $VERSION_ID)
# os_ver=$(. /etc/os-release; echo $VERSION_ID)
# echo $os_ver
8
Finally, add it into the bash script to download the EPEL repo in CentOS.
os_ver=$(. /etc/os-release; echo $VERSION_ID)
echo $os_ver
sudo yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-$os_ver.noarch.rpm
The output when I ran the script on CentOS 8.
# os_ver=$(. /etc/os-release; echo $VERSION_ID)
# echo $os_ver
8
# sudo yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-$os_ver.noarch.rpm
Last metadata expiration check: 0:58:59 ago on Sat 29 Oct 2022 11:26:49 PM EDT.
epel-release-latest-8.noarch.rpm 25 kB/s | 24 kB 00:00
Package epel-release-8-17.el8.noarch is already installed.
Dependencies resolved.
Nothing to do.
Complete!
The output when I ran the script on CentOS 7.
# os_ver=$(. /etc/os-release; echo $VERSION_ID)
# echo $os_ver
7
# sudo yum -y install https://dl.fedoraproject.org/pub/epel/epel-release-latest-$os_ver.noarch.rpm
Loaded plugins: fastestmirror
epel-release-latest-7.noarch.rpm
Examining /var/tmp/yum-root-M_B6Zy/epel-release-latest-7.noarch.rpm: epel-release-7-14.noarch
Marking /var/tmp/yum-root-M_B6Zy/epel-release-latest-7.noarch.rpm to be installed
Resolving Dependencies
--> Running transaction check
---> Package epel-release.noarch 0:7-14 will be installed
--> Finished Dependency Resolution
...
Running transaction
Installing : epel-release-7-14.noarch
Verifying : epel-release-7-14.noarch
Installed:
epel-release.noarch 0:7-14
Complete!
ADVERTISEMENT
5/5 - (1 vote)