20

I have switched to zsh, how can I run a script which is written for bash?

I don't want to modify the script to put #!/bin/bash in the beginning for the script since it is version controlled.

Is there another way?

The line of the script having problem is:

for f in `/bin/ls v/*/s.sh v/*/*/v.sh d/*/*/v.sh 2> /dev/null`
2
  • 3
    This line is terrible! It's terrible bash practice to parse the output of ls. Dec 21, 2012 at 20:56
  • 1
    I agree with @gniourf_gniourf. While it's a bit outside the scope of this question, you would be better off doing this: for f in v/*/s.sh v/*/*/v.sh d/*/*/v.sh (this uses the built in glob-substitution of bash) Dec 21, 2012 at 23:08

2 Answers 2

44

You can run the script with bash manually:

bash myscript.sh

A better and more permanent solution is to add a shebang line:

#!/usr/bin/env bash

Once that line is added, you can run it directly, even in ZShell:

% ./myscript.sh

As far as version control goes, you should commit this line, for the good of all the developers involved.

2
  • 5
    Agreed -- a script that requires bash, but doesn't start with a bash shebang, should be considered broken. And broken scripts should be fixed. (Though as @gniourf_gniourf pointed out, that's not the only problem here.) Dec 21, 2012 at 22:38
  • 1
    As long as we are on the subject of shebangs: Why not correct to #!/usr/bin/env bash. That way the scripts work on more systems. (/usr/local/bin/bash, /usr/bin/bash etc are all hardcoded and you need to fix each script for each shell you use. With env you only have to maintain one single program).
    – Hennes
    Dec 22, 2012 at 7:05
6

In addition to the solution commented by @neersighted, you should also make sure your bash script has the executive permission to run in the zsh. Thus, you should first set the first line of your bash script with shabang:

#!/usr/bin/env bash

Then run:

% chmod +x myscript.sh

to provide such permission. Then you can run it in zsh as:

% ./myscript.sh
3
  • 1
    saved me a lot of time Aug 2, 2020 at 18:07
  • This doesn't answer the question, which specifically stated: "I don't want to modify the script to put #!/bin/bash in the beginning for the script since it is version controlled." Nov 25, 2020 at 12:32
  • 1
    Future me will be back here sometime. ..
    – naim5am
    Jan 13, 2021 at 1:17

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.