26

Just trying to learn bash scripting a little. My old bash version:

Bash version 3.2.53(1)-release...

I've updated my bash on mac os x yosemite with homebrew:

brew update
brew install bash

Then in terminal properties I’ve changed the standard shell path from /bin/bash to /usr/local/bin/bash (As I understand this is where the homebrew installs the updated bash).

Then I checked the result again (and seems like it's all good):

$ echo $BASH_VERSION
Bash version 4.0.33(0)-release...

But when I was trying to write a simple bash script:

#!/bin/bash
echo "Bash version ${BASH_VERSION}..."
for i in {0..10..2}
  do
     echo "Welcome $i times"
 done

THE RESULT IS:

Bash version 3.2.53(1)-release...
Welcome {0..10..2} times

INSTEAD OF:

Bash version 4.0.33(0)-release...
Welcome 0 times
Welcome 2 times
Welcome 4 times
Welcome 6 times
Welcome 8 times
Welcome 10 times

Why the Bash version changes back to old one when I'm trying to execute script in the same shell??? This just freaks me out! Please someone explain me what's my problem)))

3 Answers 3

16

Your problem is in your first line. You have this:

#!/bin/bash

which explicitly states that the shell script should be ran with the old /bin/bash. What you really want, is this:

#!/usr/local/bin/bash

to use the new bash from /usr/local/bin.

7
  • weird thing, but it actually didn't work. Still same result((( But I'm sure this is a part of a problem
    – drew1kun
    Dec 27, 2014 at 8:41
  • Do I need to specify this path somewhere else? In some shell file or something?
    – drew1kun
    Dec 27, 2014 at 8:49
  • 1
    Maybe the environment is set by the calling shell, i.e. the old Bash? How exactly are you calling your script, @Andrew?
    – slhck
    Dec 27, 2014 at 9:26
  • 1
    @Andrew, I suspect that your sh is in /bin. brew maybe didn't make a symlink for bash called sh. With your $PATH set correctly, try starting it like this: bash script.sh.
    – BenjiWiebe
    Dec 27, 2014 at 21:40
  • 11
    For future reference, you should probably use #!/usr/bin/env bash Oct 25, 2015 at 4:19
16

Install new bash:

brew install bash

Make this the default shell:

chsh -s /usr/local/bin/bash

Set the environment in a script:

#!/usr/bin/env bash

Using env will look for Bash in your $PATH and use the first one it encounters. You can see which bash it will use by typing which bash. If it's seeing /bin/bash first, you will need to set your $PATH in ~/.bashrc and /.bash_profile.

1
7

As pjv pointed out, you really should use

#!/usr/bin/env bash

in your scripts everywhere to be portable. E.g. if you try to run your script with

#!/usr/local/bin/bash

it will fail on most linux systems.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .