3

How can I specify the shell variant for a file in that file's Emacs local variables, when the file is not a standalone program?

Emacs allows me to specify that a shell include file should be opened in sh mode, by setting a local variable in the editor hints:

# Local variables:
# coding: utf-8
# mode: sh
# End:
# vim: fileencoding=utf-8 filetype=bash :

I can specify to Vim that the file's shell variant is specifically Bash, and it obeys the editor hint to present specific Bash syntax highlighting. But Emacs has sh mode which covers all shell variants.

Emacs will properly interpret such a file if it has a shebang line (e.g. #! /bin/bash). But some files are not stand-alone programs, so I do not want those to have a shebang line.

Emacs sh mode treats those files as Posix shell syntax, which they are not. sh mode has the concept of “variant” of shell syntax; but I'm unable to find out how to specify, in the file's editor hints, which variant to use for the file.

How can I set the editor hints in the file to tell Emacs that its syntax is Bash?

Update 2014-04-24: I have reported Emacs bug#17333 for this missing behaviour.

2
  • bignose's bug report has been fixed. So in the next Emacs release (presumably 24.5), this really will be as easy as setting sh-shell as a file-local variable. Yay! Until then, my answer below really does work without adding an explicit shebang line (notwithstanding bignose's initial impression to the contrary).
    – Ben Liblit
    Jun 25, 2014 at 15:35
  • The fix to bugnose’s bug report appears in Emacs 25.1. The NEWS file states that “In sh-mode you can now use sh-shell as a file-local variable to specify the type of shell in use (bash, csh, etc).”
    – Ben Liblit
    Jul 11, 2016 at 20:19

1 Answer 1

2

Looking at the sh-mode code, it seems that someone may have intended to allow this by setting sh-shell or perhaps sh-shell-file as a file-local variable. Neither actually works, though. Please consider submitting a bug report to the sh-mode maintainer about this. It really seems like it should be as easy as adding sh-shell: bash to your file-local variables block, and that may have even been the original intent, but it just doesn’t work.

What does work is either of the following:

  1. Name your file something ending in .bash.

  2. Add eval: (sh-set-shell "bash") to your file-local variables block. By default Emacs will show a warning that this might be unsafe code, though that can be disabled.

2
  • The sh-set-shell command does the wrong thing: it adds a shebang line, to a file that specifically should not have one.
    – bignose
    Apr 24, 2014 at 0:08
  • sh-set-shell only adds a shebang line when called interactively, or with a non-nil third argument. When called as I suggest above, it does not add a shebang line. Try it and see for yourself.
    – Ben Liblit
    Apr 24, 2014 at 15:33

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .