1

So I want to figure out the Operating System and execute a piece of code based on the operating system in my .vimrc. However, I'm not able to understand where I'm going wrong.

let operating_system = system("awk -F= '/^NAME/{print $2}' /etc/os-release")
echon operating_system
echon operating_system > "CentOS Linux"
echon operating_system < "CentOS Linux"
echon operating_system ==? "CentOS Linux"
echon operating_system ==# "CentOS Linux"

This is the output I get when I start vim:

"CentOS Linux"
0100

Shouldn't ==? and ==# evaluate to 1? If not, why?

2

It's not working, because what you have inside operating_system variable is a bit more, than just CentOS Linux. First of all, those quotes " are part of the string. Checkout contents of that file. If you use = as a separator, second field actually contains " characters (at least that's the case on my system). Also, there probably is some invisible magic character at the end of string - carrige return or new line.

This should work if you change getting the operating_system variable to this:

let operating_system = join(split(system("sed -n 's/^NAME=\"\\([^\"]\\+\\)\".*$/\\1/p' /etc/os-release")))

sed will get everything inside " " part (I don't know awk that well to do this with it), and the join/split combo will remove those invisible characters.

2

Note that you don't need to execute external processes with system() which adds trailing newlines & all.

let os = matchstr(filter(readfile('/etc/os-release'), 'v:val =~ "^NAME"')[0], '.*"\zs.*\ze".*')

with:

  • readfile() to read the system file
  • filter() to keep only the line with NAME=
  • matchstr() with extract the content of the name field (in the first line [0])

BTW, /etc/redhat-release also has the information you're looking for.

let is_centos = readfile('/etc/redhat-release')[0] =~ 'CentOS Linux'
  • Hey, thanks for the reply! Your method works too! About parsing the /etc/redhat-release file, I think I'll be sticking to /etc/os-release would be better since its a generalized solution and if it is some other OS I'm working on, I can customize based on the output. – codingCoffee Jul 13 '18 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.