Home > OS >  Different result from bash and source commands
Different result from bash and source commands

Time:11-18

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

CodePudding user response:

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.

CodePudding user response:

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.

  • Related