Search code examples
shellvimsyntaxyoucompleteme

Wrong syntax highlight for shell script in vim


I'm new to vim and shell script. I'm not sure if there is a real problem or it is just me not understanding vim or shell script, but I did search through the google and got no answer. Anyway, this is what I got when I doing shell script in vim. And I think the syntax highlight is not working correctly.

See image click here

filename=$(basename $file)

Vim highlights the $( and ) in red colour.

BTW: I'm using gvim 8.0 on Mac and had YCM installed, if it is relevant.


Solution

  • This has to do with the behavior of Vim's shell syntax. It has three modes: posix shell, ksh, and bash. You are using bash syntax, but Vim is rendering it as posix shell (the default).

    Here is a screenshot of 3 different versions of this code in Vim 8.0.

    enter image description here

    The top version is just the code you posted in your screenshot. By default, it is using posix shell mode, and you can see that the red highlights are present.

    In the middle version, I have added #!/bin/sh to the beginning of the file. This is still in posix mode, and still has the red highlights.

    At the bottom, you can see I switched to #!/bin/bash. This triggers the bash behavior, and now you can see the bash-specific syntax is no longer marked as an error.

    The #! line is used to auto-detect the file type. However, if it is missing, it is still possible to force the mode, if you wish to.

    :let b:is_bash=1
    :set ft=sh
    

    Note that the mode is set when the file is opened. So adding #!/bin/bash won't immediately fix the mode. You would need to save/exit the file, and then open it again, to switch to bash mode. (Or use the trick just above this paragraph.)