This seems like a basic thing yet I can’t get it work properly. I have a bash script where I want to compare the OS version (11 or 12 in Debian’s case) and do something depending on the version. Here is what I have:
if [ cat /etc/*release | sed -n '3p' | cut -c 13-14 == '12' ]
then
perform actions
The command above works on the command line on Debian 11 (without the comparison) and prints out either 11 or 12. However, running it on Debian 12 says it is Debian 11. Does anyone know what I am doing wrong?
2
Answers
For starters, a UUoC. Why
cat file|sed
? Justsed -n '3p' /etc/*release
. I’d also skip the extraneouscut
. On my Centos:sed -n '/^VERSION=/{s/[^0-9]//g;p}' /etc/*release
gives me7
. Likewise, if you are usingbash
you should almost always use[[...]]
instead of[...]
, for several reasons, though there are arguments on either side – just know the syntax for whichever you are using.The real problem here, though, is that you need a
$(...)
subshell, or at least backticks.I recommend the first one, the
grep
with no brackets at all, which is doing exactly what you want without embedding it into some other syntax. (Obviously you’d want to change the 7 to a 12, or some appropriate pattern, but I recommend keeping the quotes.)When something isn’t working, paste your code at ShellCheck. It will often help.
You should also confirm that the record you want looks like the pattern I’m checking in Debian. You’re apparently looking at
VERSION_ID
(I was checkingVERSION
) so I updated that.output: