将 csv 字符串拆分为适用于 bash 和 zsh 的数组的最简单方法

XDR*_*XDR 3 arrays string bash split zsh

仅使用适用于 bash 和 zsh 的内置函数将 csv 字符串拆分为数组的最简单方法是什么?

我有适用于 bash 和 zsh 的单独代码,但我还没有找到任何适用于这两者的代码:

csv='a,b,c'

# Works in zsh, but not in bash
array=(${(s:,:)csv})

# Works in bash, but not in zsh
array=(${csv//,/ }) # This requires that $IFS contains the space character
Run Code Online (Sandbox Code Playgroud)

che*_*ner 7

As pointed out in the comments, there are two nearly identical commands, one for each shell.

# bash
IFS=, read -ra array <<< "$csv"

# zsh
IFS=, read -rA array <<< "$csv"
Run Code Online (Sandbox Code Playgroud)

The syntax is the same; the only difference is whether you use a or A as the option to read. I would recommend adding a conditional statement that detects which shell is executing the script, then use a variable to store the correct option.

if [ -n "$BASH_VERSION" ]; then
    arr_opt=a
elif [ -n "$ZSH_VERSION" ]; then
    arr_opt=A
fi

IFS=, read -r"$arr_opt" array <<< "$csv"
Run Code Online (Sandbox Code Playgroud)

Checking for non-empty version parameters isn't foolproof, but it should be good enough.