0
#!/bin/bash

myvar="string 1,string 2,string 3"

# Here comma is our delimiter value
IFS="," read -a myarray <<< $myvar

echo "My array: ${myarray[@]}"
echo "My array [0]:" ${myarray[0]}
echo "Number of elements in the array: ${#myarray[@]}"

for (( i=0; i<=${#myarray[@]}; i++ )); do
     echo "${myarray[$i]}"
done

When I execute the script above, Bash on Mac OS outputs it like this...

i5-Mac-mini:~ macmini$ ./testarray.sh
My array: string 1 string 2 string 3
My array [0]: string 1 string 2 string 3
Number of elements in the array: 1
string 1 string 2 string 3

String 1, String 2, and string three are all on the same line. I want them on separate lines like it does with Bash in Ubuntu Linux.

fflintstone@bedrock:~$ ./testarray.sh
My array: string 1 string 2 string 3
My array [0]: string 1
Number of elements in the array: 3
string 1
string 2
string 3

Whats going on?

I've tried inserting /n, /r, /c at the end of the echo. I've tried printf with no luck. It seems to me it has something to do with my environment setup.

  • This was a known bug, fixed years ago, but macOS continues to ship a very old version of `bash`. Best to treat that as a shell limited to POSIX compliance, and install a new version of `bash` yourself or use `zsh`. – chepner Nov 15 '22 at 21:36
  • I'm agree with @chepner. Check your bash version with `bash --version` command. You could install bash version 5 with brew (https://brew.sh/) bash formulae like this : https://stackoverflow.com/questions/10574969/how-do-i-install-bash-3-2-25-on-mac-os-x-10-5-8 – Arnaud Valmary Nov 15 '22 at 21:37
  • 1
    The easiest workaround is to simply quote `$myvar`. – chepner Nov 15 '22 at 21:37
  • 1
    /me grumbles about Homebrew's gawdawful so-called security model. (Personally, I advocate for Nix as a first-choice package manager, Macports as second-choice, Homebrew for when there's no feasible alternative) – Charles Duffy Nov 15 '22 at 21:44
  • Thanks chepner. That was the only variable I didn't quote and tried your suggestion and that work! – Fred Flintstone Nov 15 '22 at 22:48
  • Thanks for the other suggestions. I wouldn't mind having bash on the Mac and bash on Linux be as close to the same version as possible. – Fred Flintstone Nov 15 '22 at 22:50

0 Answers0