How to highlight Bash scripts in Vim?
Solution 1:
Are you correctly giving the shell script a .sh
extension? Vim's automatic syntax selection is almost completely based on file name (extension) detection. If a file doesn't have a syntax set (or is the wrong syntax), Vim won't automatically change to the correct syntax just because you started typing a script in a given language.
As a temporary workaround, the command :set syn=sh
will turn on shell-script syntax highlighting.
Solution 2:
The answers so far are correct that you can use the extension (like .sh
) or a shebang line (like #!/bin/bash
) to identify the file type. If you don't have one of those, you can still specify the file type manually by using a modeline comment at the top or bottom of your file.
For instance, if you want to identify a script without an extension as a shell script, you could add this comment to the top of your file:
# vim: set filetype=sh :
or
# vim: filetype=sh
That will tell vim to treat the file as a shell script. (You can set other things in the modeline, too. In vim type :help modeline
for more info.)
Solution 3:
Actually syntax highlighting is a feature of vim not vi. Try using vim command and then do
:syntax on
.
Solution 4:
I came to this answer looking for specifically how to highlight bash
syntax, not POSIX shell. Simply doing a set ft=sh
(or equivalent) will result in the file being highlighted for POSIX shell, which leaves a lot of syntax that's valid in bash
highlighted in red. To get bash highlighting:
" Set a variable on the buffer that tells the sh syntax highlighter
" that this is bash:
let b:is_bash = 1
" Set the filetype to sh
set ft=sh
Note that if your ft
is already sh
, you still need the set
command; otherwise the let
doesn't take effect immediately.
You can make this a global default by making the variable global, i.e., let g:is_bash = 1
.
:help ft-sh-syntax
is the manual page I had to find; it explains this, and how to trigger highlighting of other flavors of shell.