Issue
#!/bin/bash
if rpm -q sudo > /dev/null; then
echo "sudo is installed and version is"
else
echo "sudo is not installed"
fi
hi was wondering if it is possible to print out my sudo version after checking that it is installed. If there's a way, how can I do it
Solution
sudo --version
output must be parsed and the return status used to determine if it is installed.
First of all, you want the version output to be consistent, regardless of active system locale.
So you invoke it with LANG=C sudo --version
.
This prints multiple lines and only the first line last element is the sudo version:
Sudo version 1.9.5p2
Sudoers policy plugin version 1.9.5p2
Sudoers file grammar version 48
Sudoers I/O plugin version 1.9.5p2
Sudoers audit plugin version 1.9.5p2
Using POSIX-shell grammer, lines and field parsing must be done with external tools. Here awk
is capable of parsing it all at once:
#!/usr/bin/env sh
# Captures version string parsed with awk:
# so only last entry of first line is captured
if sudo_version=$(LANG=C sudo --version 2>/dev/null | awk 'NR==1{print $NF}')
then printf 'sudo is installed and version is %s\n' "$sudo_version"
else printf 'sudo is not installed\n' >&2
fi
If using Bash, capturing the first line into an array save from using external tools and pipe forking process:
#!/usr/bin/env bash
# Capture version string first line into a Bash array
if read -ra version_array < <(LANG=C sudo --version 2>/dev/null)
then
# Version is the last element of array
printf 'sudo is installed and version is %s\n' "${version_array[-1]}"
else
printf 'sudo is not installed\n' >&2
fi
Answered By - Léa Gris Answer Checked By - Marilyn (WPSolving Volunteer)