Home > database >  Weird behaviour when running shell script with `source` and without
Weird behaviour when running shell script with `source` and without

Time:11-19

I am expecting the same result when running the below script with source and without. Is weird that it is giving me a different result when I ran with source and without source.

Shell script

#!/usr/bin/env bash

flag="$1"

for i in ${flag//=/ }; do
    echo "item: $i"
done

Execution with source

$ . ./test.sh -p=test
item: -p test

$ source ./test.sh -p=test
item: -p test

Execution without source

./test.sh -p=test
item: -p
item: test

Can someone tell me what different when I ran with source and without ? I tried /bin/bash, /bin/sh...., still the same problem.

CodePudding user response:

The issue is that source runs in the same shell you are currently running in and ./ opens it up into a subshell.

What is happening is you are setting IFS in your current shell probably in your .bashrc to a value that does not include a space (something like $'\n'), which does not get inherited when running ./ but does when using source

To fix just reset IFS back to its default value:

IFS=$' \t\n'
source test.sh -p=test
item: -p
item: test
  • Related