Bash – How to map one vim command to execute bash commands based on OS

bashvim

In short, can single bash commands in the terminal contain conditionals? If so, how?

I have in my vimrc (shared across systems) the following command to open my current LaTeX document in .pdf form:
map ,v :!gnome-open %<.pdf <CR> <CR>

My question is, what is the best way to have ,v execute simply "open %<.pdf" when I'm at home on my OS X machine? Here is my pseudo-code guess:

... if [$OSTYPE == "darwin*"] then open %<.pdf else gnome-open %<.pdf ...

This is executed as a single BASH command. Are such conditionals possible? If so, could someone help me with the syntax? If not, can this be done via conditionals in the vimrc file?

Best Answer

An alternate would be to just generate the map keybinding correctly for the OS. For example:

if executable("cmd.exe")
    map ,v :!cmd.exe /C start "" "%<.pdf"<CR><CR>
elseif $OSTYPE =~ "darwin.*"
    map ,v :!open '%<.pdf'<CR><CR>
elseif executable("gnome-open")
    map ,v :!gnome-open '%<.pdf'<CR><CR>
endif

This was tested and appears to work, but as my Vim script is a little shaky and I might have missed some details like proper quoting, I'd probably go more with Jander's approach and just use a shell wrapper which I am far superior in writing.

map ,v :!open.sh '%<.pdf'<CR><CR>

And in ~/bin/open.sh:

#!/bin/sh

if echo "$OSTYPE" | grep "^darwin" >/dev/null 2>&1; then
    open "$@" &
elif type gnome-open &>/dev/null; then
    gnome-open "$@" &
fi
Related Question