简体   繁体   中英

Bash shebang is ignored - script is still executed with zsh

I have a script on Mac OSX which is executed when opening a new terminal. It is specified in .zprofile . It has a bash shebang but it is still executed with zsh (my default shell). What may be the problem here?

#!/bin/bash

The core problem is that I am not able to execute the script due to differences of zsh syntax. When I analysed what may cause this, I recognised that the shebang is just ignored.

I have a binary /bin/bash btw.

Edit:

~/.zprofile executes the script like so:

. ~/.script.bash

You have written in you ~/.zprofile the following line:

. ~/.script.bash

This is similar to

source ~/.script.bash

Which implies that your script is sourced and not executed. You should have something like:

~/.script.bash

instead which will execute in the environment defined by the shebang. Note that the file needs to be executable.

. file [ arg ... ] . file [ arg ... ] : Read commands from file and execute them in the current shell environment.

source: man zshall

When you "source" a script file (ie . <script-file-name> ) the commands in the file are executed in the current shell, using the syntax of the current shell. Any "shebang" line in the file is interpreted as a shell comment and is ignored.

If the shell commands in your script file can be run by executing the file, you can make it an executable file and run it as a command.

However when you execute a shell script, the execution happens in a child process. That means that things that need to alter the state of the current shell / process won't work. Things like:

  • changing this shell's environment variables
  • defining this shell's functions or aliases
  • changing this shell's working directory
  • changing this shell's ulimits
  • and so on

If you need to do that kind of thing, you have no alternative but to translate your bash script into a zsh script so that you can "source" it in zsh .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM