【问题标题】:How do I print all the elements in my bash array? [duplicate]如何打印 bash 数组中的所有元素? [复制]
【发布时间】:2019-04-01 15:07:10
【问题描述】:

我在 bash 中运行此脚本以将用户列表添加到数组中,然后将其写入文件。这是脚本:

echo "Insert the first user of the list"
read -r user_name
user_list=()
echo "User $user_name inserted!"
user_list+=($user_name)

echo "Do you want to insert another user?(yes or no)"
read -r answ
while [ $answ == "yes" ]; do
     echo "Enter a new user to insert"
     read -r new_user
     user_list+=($new_user)
     echo "Users list contains:"
     echo "$user_list"
     echo "Do you want to add another user?(yes or no)"
     read -r answ
done

echo "$user_list" > user_list.txt;

除了数组只包含第一个元素之外,一切正常。我不明白为什么 $new_user 没有添加到数组中。

【问题讨论】:

  • bash 数组仅在使用其名称调用时打印第一个元素。
  • 试试echo "${user_list[@]}"
  • 使用echo "${myArray[*]}"

标签: bash terminal


【解决方案1】:

最后一行可能是

printf "%s\n" "${user_list[@]}" >user_list.txt

【讨论】:

    猜你喜欢
    • 2021-04-07
    • 2015-07-28
    • 2015-01-31
    • 2014-05-05
    • 1970-01-01
    • 2019-02-26
    • 2013-05-06
    • 2021-06-06
    • 1970-01-01
    相关资源
    最近更新 更多