创建一个 bash 数组,以新行分隔

Creating a bash array, separated by new lines

我正在从一个看起来像这样的 .txt 文件中读取:

:DRIVES
name,server,share_1
other_name,other_server,share_2
new_name,new_server,share 3
:NAME

这是挂载驱动器的信息。我想将它们加载到 bash 数组中以循环并挂载它们,但是我当前的代码在第三行中断,因为该数组是由任何白色 space 创建的。而不是阅读

new_name,new_server,share 3

作为一行,它读作 2 行

new_name,new_server,share 
3

我试过将 IFS 的值更改为

IFS=$'\n' #and
IFS='
'

但是都不起作用。如何从上面的文件创建一个数组,用换行符分隔。我的代码如下。

file_formatted=$(cat ~/location/to/file/test.txt)
IFS='
' # also tried $'\n'
drives=($(sed 's/^.*:DRIVES //; s/:.*$//' <<< $file_formatted))

for line in "${drives[@]}"
do
  #seperates lines into indiviudal parts
  drive="$(echo $line | cut -d, -f2)"
  server="$(echo $line | cut -d, -f3)"
  share="$(echo $line | cut -d, -f4 | tr '\' '/' | tr '[:upper:]' '[:lower:]')"

#mount //$server/$share using osascript
#script breaks because it tries to mount /server/share instead of /server/share 3

编辑:

尝试了这个并获得了与以前相同的输出:

drives=$(sed 's/^.*:DRIVES //; s/:.*$//' <<< $file_formatted)
while IFS= read -r line; do
  printf '%s\n' "$line"
done <<< "$drives"

这是迭代文件的正确方法;不需要数组。

{
  # Skip over lines until we read :DRIVES
  while IFS= read -r line; do
    [[ $line = :DRIVES ]] && break
  done

  # Split each comma-separated line into the desired variables,
  # until we read :NAMES, wt which point we break out of this loop
  while IFS=, read -r drive server share; do
    [[ $drive == :NAMES ]] && break
    # Use $drive, $server, and $share
  done

  # No need to read the rest of the file, if any
} < ~/location/to/file/test.txt