linuxbashmacosshellzsh

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


Solution

  • 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.