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)))

Giacomo1968
  • 58,727
drew1kun
  • 2,207

3 Answers3

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.

Will
  • 403
Ben
  • 261
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.

BenjiWiebe
  • 9,173
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.