In Shell-script[bash] mode, coloring differs for sh-quoted-exec in #!/bin/sh and #!/bin/bash.

If #!/bin/sh is the first line: // I prefert this enter image description here

If #!/bin/bash is the first line: enter image description here

Would it be possible to have same coloring in sh for bash?


You can manually toggle which features Emacs will apply to your file via M-x sh-set-shell: pick /bin/sh to get the variant you prefer. You can set this automatically for a file by adding the following code at the end of the file:

# Local Variables:
# sh-shell: sh
# End:

To illustrate, with this file:

alper=$(gdrive list --query "'$id' in parents" --no-header | grep "patch_")

# Local Variables:
# sh-shell: sh
# End:

I see this:

enter image description here

It doesn't change the #! directive on the first line, and I get the syntax highlighting of the sh style in a bash script. This is with Emacs 28.0.50, started with emacs -Q.

To enable this automatically for all bash scripts, you can use the following hook:

(defun my-set-shell ()
  (sh-set-shell "sh"))

(add-hook 'sh-mode-hook 'my-set-shell)
  • Inside $() when the complete string colored in same its hard to understand. Like strings ("blabla") was in green. Only the gdrive on the example colored into maganta and its parementers except "'$id' in parents" was white
    – alper
    Aug 24 '21 at 10:36
  • I have select sh but it changes #!/usr/bin/bash into #!/usr/bin/sh. I want to keep it as #!/usr/bin/bash if possible and apply the sh's theme into #!/usr/bin/bash. Please note that I didn't have this issue on emacs 27 or 26
    – alper
    Aug 24 '21 at 10:38
  • I can't reproduce this here. I'm using Emacs 28.0.50. I've updated my answer to show you exactly how the buffer appears to me.
    – Tyler
    Aug 24 '21 at 13:20
  • Same here I am using 28.0.50 as well, where there was no issue on versions below 28.0. Can I have this solution without having Local Variables written below? I have plenty of *.sh file and it will be difficult to make changes on all
    – alper
    Aug 24 '21 at 18:34
  • I added a hook that should handle this automatically
    – Tyler
    Aug 24 '21 at 19:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.