nhthai
nhthai

Reputation: 318

Different result from bash and source commands

I have a very simple script name tt.sh like this:

listFile=("A" "B" "C" "D")
echo ${listFile[1]} ${listFile[2]}

I tried to test this script with source and bash, but get a different result:

./tt.sh 
B C
source tt.sh
A B

Why does the source command take the start of the array from 1 instead of 0? I'm using MacOS

enter image description here

Upvotes: 1

Views: 312

Answers (3)

Al Sweigart
Al Sweigart

Reputation: 12939

This behavior happens because source is running zsh and not bash. Your version of macOS must be using zsh by default instead of bash. On bash, array indexes start at 0 but on zsh array indexes start at 1.

You can determine your shell by running echo $0. (On my macbook, it shows /bin/zsh.)

Upvotes: 0

Sam Daniel
Sam Daniel

Reputation: 1902

When you source it the current shell is used, and when you execute the executable mentioned in shebang is used.

bash index starts from 0, some other shells have array index start at 1.

Most likely your current shell is not bash.

Upvotes: 2

Rudy Matela
Rudy Matela

Reputation: 6460

I don't have a Mac, but here's what I can reproduce on Arch Linux (2021):

$ cat >tt.sh 
listFile=("A" "B" "C" "D")
echo ${listFile[1]} ${listFile[2]}
^D

$ bash tt.sh 
B C

$ zsh tt.sh 
A B

When I run the script with bash, it shows B C. When I run with zsh, it shows A B.

Are you really using bash on the terminal you're sourcing to? You can double-check with:

$ echo $0
bash

If the above shows bash, it means you are. If it shows zsh, it means you are using zsh so you will see the zsh behaviour when you source.

Starting with macOS Catalina, the default is zsh. If you would really like the bash behaviour, you could try swiching your default shell on Mac settings.

Upvotes: 1

Related Questions