The script should be able to detect the operating system that is running.
The alternatives OS is Arch Linux, Centos and Ubuntu.
os=$(uname)
if [ "$os" == "Arch" ]; then
echo "Arch Linux detected"
elif [ "$os" == "CentOS" ]; then
echo "CentOS detected"
elif [ "$os" == "Ubuntu" ]; then
echo "Ubuntu detected"
else
echo "Unknown OS detected"
fi```
Output: Unknown OS detected
I tried doing this:
`del1()
{
os=$(cat /etc/os-release | grep "PRETTY_NAME")
}
del1
echo "The operating system is: $os"`
The output: PRETTY_NAME="Ubuntu 20.04.2 LTS"
But I want to check between Centos, Arch Linux and Ubuntu.
Any suggestions?
3
Answers
You can use the grep command to filter the output of the
cat /etc/os-release
command for specific strings that indicate the operating system.For example, you could use the following command to check for Ubuntu:
You could then use an if statement to check if the variable os equals to Ubuntu:
You can do the same to check for Arch Linux:
And for Centos:
You can also use
cat /etc/*-release
instead ofcat /etc/os-release
for more general detection of the OS.You can also use
lsb_release -a
command to get more details about the distribution and version of the OS.You can then create a function that check for each os one by one and print the output accordingly.
Please note that this approach might not be 100% accurate and it is better to use the appropriate package manager commands to check the OS version and distribution.
The
uname
command will always returnLinux
when running on Linux, so of course that’s never going to work.Using
/etc/os-release
is probably the best solution, but don’tgrep
it for information; the file is a collection of shell variables that you can source with the.
command, so you can write something like this:If you just need to check the name of the OS, you can try;