【发布时间】:2020-11-06 06:45:43
【问题描述】:
所以我的 CSV 文件看起来像这样:
repo_name1,path1,branch1 branch2
我用以下代码阅读它:
INPUT=repos.csv
OLDIFS=$IFS
IFS=','
[ ! -f $INPUT ] && { echo "$INPUT file not found"; exit 99; }
while read repo_name local_path branches
do
printf "\n"
echo "Repository name: $repo_name"
echo "Local path: $local_path"
cd $local_path
for branch in $branches
do
echo branch
printf "\n"
done
done < $INPUT
IFS=$OLDIFS
我想在 bash 脚本中将 branch1 和 branch2 拆分为一个数组。
我尝试了我在 stackoverflow 上找到的所有内容
Loop through an array of strings in Bash?,
Split string into an array in Bash,
Reading a delimited string into an array in Bash
,但没有任何工作正常,我得到的是包含 1 个元素的数组 -> branch1 branch2
任何想法我做错了什么?
【问题讨论】:
-
您已设置
IFS=','并尝试读取以空格分隔的数组 -
尝试
IFS=",$IFS"添加逗号,但保留通常的分隔符。 (而echo branch应该是echo "$branch"。) -
for branch in $branches-- 您使用 IFS= 来拆分$branches,$branches 中没有逗号,因此您只能通过该循环进行一次迭代。