Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash shebang is ignored - script is still executed with zsh

Tags:

macos

shebang

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
like image 524
OddDev Avatar asked Dec 24 '22 01:12

OddDev


2 Answers

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 ... ]: Read commands from file and execute them in the current shell environment.

source: man zshall

like image 167
kvantour Avatar answered Jan 05 '23 16:01

kvantour


When you "source" a script file (i.e. . <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.

like image 22
Stephen C Avatar answered Jan 05 '23 17:01

Stephen C