I'm trying to write a bash function that will take a command such as xcode-select -v
or brew -v
that outputs a lot of extra text, and format it to my liking. Just to further the example, say I run xcode-select -v
, it will output xcode-select version 2333.
. I want to be able to split this string up and only take the 2333
part so I can put it in an echo
statement. I want the same function to be able to handle the various outputs of stuff like brew -v
, or git --version
, etc.
get_version_number() {
# set local variable to executed arguments that is passed in
local command="$($@)"
# set up temp variable and assign to global IFS variable
OIFS=$IFS
# set up IFS to split the string on empty space
IFS=" "
# read commands output into an array and store it in $array variable
read -a array <<< "$command"
# clear out IFS back to what it original was for further use
IFS=$OIFS
# echo out array at a particular indices that should be passed in
echo ${array[@]}
}
# store output of this command into variable for further usage
version=$(get_version_number xcode-select -v)
echo $version
Edit 1: Originally the idea came from me having to copy/paste these same lines within different conditional blocks...
command=$(git -v)
OIFS=$IFS
IFS=" "
read -a output_array <<< "$command"
IFS=$OIFS
printf "Git version ${output_array[2]} is installed."
command=$(brew -v)
OIFS=$IFS
IFS=" "
read -a output_array <<< "$command"
IFS=$OIFS
printf "Homebrew version ${output_array[1]} is installed."