0

I am trying to check if the gcc version and based on the result execute another system call (scl enable devtoolset-7 bash).

Below is what I have tried so far

gcc --version | awk '/gcc/ && ($3+0)<7.0{print "Current Version",$3,"is less than 7.5" system("scl enable devtoolset-7 bash")}'

I wish to know how to get this done correctly in awk. Also, I am open to other simpler approaches to do the above, if any.

user2532296
  • 828
  • 1
  • 10
  • 27
  • Wat do you want to compare? – 0stone0 Nov 22 '22 at 13:43
  • I wish to compare the gcc version of the current system against 7.0 – user2532296 Nov 22 '22 at 13:44
  • Do you need 'less' than or 'larger' than? Then you'll need [to compare the versions](https://stackoverflow.com/questions/4023830/how-to-compare-two-strings-in-dot-separated-version-format-in-bash), otherwise you can just use `!=` – 0stone0 Nov 22 '22 at 13:46
  • I need 'less' than. If the gcc version is less, then I need to execute the command ```scl enable devtoolset-7 bash``` as shown above – user2532296 Nov 22 '22 at 13:49
  • You'll need a semicolon (or newline) between the print statement and the system call. – glenn jackman Nov 22 '22 at 14:42

1 Answers1

2

Don't complicate things by having awk spawn a subshell to call another command if you don't have to:

if [[ gcc --version | awk '/gcc/ && ($3+0)<7.0{print "Current Version",$3,"is less than 7.5"; f=1} END{exit !f}' >&2 ]]; then
    scl enable devtoolset-7 bash
fi

Note that your test is <7.0 but message says <7.5. You might want to make it this instead to ensure consistency:

if [[ gcc --version | awk -v minVer='7.0' '/gcc/ && ($3+0)<(minVer+0){print "Current Version",$3,"is less than",minVer; f=1} END{exit !f}' >&2 ]]; then
    scl enable devtoolset-7 bash
fi

In general software versions can't be directly compared as either strings or numbers, though, so you might have to think about your comparison. e.g. if you wanted to compare 1.2.3 vs 1.2.4 both would be truncated to 1.2 in a numeric comparison and declared equal, but if you wanted to compare 2 different versions like 12.3 vs 5.7, the 5.7 would be considered larger in a string comparison.

Ed Morton
  • 188,023
  • 17
  • 78
  • 185