dylanaraps / pure-bash-bible

📖 A collection of pure bash alternatives to external processes.
MIT License
36.41k stars 3.27k forks source link

Inaccurate Caveat for `split()` #118

Open terminalforlife opened 2 years ago

terminalforlife commented 2 years ago

https://github.com/dylanaraps/pure-bash-bible#split-a-string-on-a-delimiter

This function works as intended in >= 3.1, unless I'm forgetting something. Prior to 3.1, you'll likely incorrectly see single-quotes in the output, if it even gets that far.

Tested on all full releases of BASH, from 3.0 to 5.1.8.

My approach would be:

split() {
    IFS=$1 read -a Buffer <<< "$2"
    printf '%s\n' "${Buffer[@]}"
}

It's even more portable, available in at least >= 3.0. The original is considerably convoluted, in my opinion.

One thing worth keeping in mind is that a here string in BASH returns an empty line if a null value is given to it, because of the newline character BASH adds after the fact, but given the nature of this function, I don't think that's a problem here.