TransWikia.com

Shell syntax highlighting

Vi and Vim Asked on August 31, 2021

I’ve noticed in bash/shell it highlights $(...) in red, for example:

enter image description here

However, if I change the syntax from ft=sh to ft=bash, it does not do this:

enter image description here

What’s the reason for this? Am I doing something wrong with the ft=sh, or why is that highlighted in red when it’s a legitimate syntax construct?

2 Answers

This is because the original Bourne shell only understands `...` - the standard $( ... ) syntax was added later. From syntax/sh.vim:

" $() and $(()): {{{1
" $(..) is not supported by sh (Bourne shell).  However, apparently
" some systems (HP?) have as their /bin/sh a (link to) Korn shell
" (ie. Posix compliant shell).  /bin/ksh should work for those
" systems too, however, so the following syntax will flag $(..) as
" an Error under /bin/sh.  By consensus of vimdev'ers!

You can set the variable g:is_bash to tell the sh syntax file that sh is actually bash, if indeed it is actually bash (does sh --version show the Bash version?). Or you can set g:is_posix if sh is POSIX compliant.

Correct answer by muru on August 31, 2021

Shell originally used only backticks for command substitution:

less `find . -type f`

But these do not nest and suffer from other problems. Bash (and probably ksh, but I’m not up on the history there) used $() as a newer, improved command substitution.

But that explains the difference and while the filetype matters—in fact, the shebang (#! line) matters! If you use /bin/sh, you should only use POSIX sh features. Otherwise, use the path to a known interpreter and use it’s features.

As pointed out in the comments, POSIX allows the newer command substitution, so it should be safe even in sh scripts.

Answered by D. Ben Knoble on August 31, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP