Vim inconsistently syntax highlighting bash files

syntax highlightingvimvim-syntax-highlighting

When I open some bash script files with vim it sometimes identifies them as conf files, that's okay, I can just correct that by setting the filetype to sh with :setf sh.

That great, except I've noticed that this doesn't fix things entirely:

Two files side-by-side with different highlighting

Notice that shopt is properly highlighted on the left, but not on the right, where I manually set the filetype to sh.

This means that when a file is identified as bash or sh by vim, it sets the filetype to sh but then does some extra steps that I'm not doing when I set the filetype manually.

Any one know what that might be, and how I could fix it?

Best Answer

vim already recognizes many file types by default. Most of them work by file extensions, but in a case like this, vim will also analyze the content of the file to guess the correct type.

vim sets the filetype for specific file names like .bashrc, .tcshrc, etc. automatically. But a file with a .sh extension will be recognized as either csh, ksh or bash script. To determine what kind of script this is exactly, vim reads the first line of the file to look at the #! line.

If the first line contains the word bash, the file is identified as a bash script. Usually you see #!/bin/bash if the script is meant to be executed directly, for some other shell configuration file you should use the file extensions .bash.

The help in vim explains this as well at :help ft-bash-syntax. You can also use let g:is_bash=1 in your .vimrc to make bash syntax highlighting the default for all files with filetype=sh. If you want to look at the details, this is implemented in $VIMRUNTIME/filetype.vim.