3

I have ZSH as default shell in MacOS, everything is working fine. ZSH is installed as brew package, Ive set default shell in my account, new shell is listed in /etc/shells... everything is set, like I've said.

I have some shell scripts in which I use some commands from zsh, like print. When I execute the script from command line, the print command is not recognized and the script fails.

This script does not have the shebang line. When I put the shebang line for zsh, then everything works; the print command is working.

Since I am using only ZSH, is it possible to set default shell for running scripts, so I don't have to put shebang line in my .zsh scripts?

Or is it possible to associate .zsh extension to ZSH shell execution?

Igor Spasic
  • 279
  • 1
  • 2
  • 14

1 Answers1

5

The Z shell uses /bin/sh if you run an executable script without shebang line (see man zshmisc, section COMMAND EXECUTION or check out this answer for a comprehensive list). This seems hard-coded. So, if you don't want to use the unix-way (add shebang line), you can use a socalled suffix alias in the Z shell to execute all files with a certain extension with a certain program. In your case

alias -s zsh=zsh

should do the trick. The general form is (as the above example is not so clear):

alias -s extension=program

The man page explains how this works:

If the -s flag is present, define a suffix alias: if the command word on a command line is in the form text.name, where text is any non-empty string, it is replaced by the text value text.name. Note that name is treated as a literal string, not a pattern.

A trailing space in value is not special in this case. For example,

alias -s ps=gv

will cause the command *.ps to be expanded to gv *.ps. As alias expansion is carried out earlier than globbing, the *.ps will then be expanded. Suffix aliases constitute a different name space from other aliases (so in the above example it is still possible to create an alias for the command ps) and the two sets are never listed together.


If you want to use scripts that are located somewhere in your $PATH, use

alias -s zsh="zsh -o PATH_SCRIPT"

This enables the option PATH_SCRIPT:

If the option PATH_SCRIPT is set, and the file name does not contain a directory path (i.e. there is no `/' in the name), first the current directory and then the command path given by the variable PATH are searched for the script.

Please note, that the current directory is searched for the script, even if . is not in your PATH!

mpy
  • 28,816