用用户输入值填充动态数组

Filling dynamic array with user input value

我是 shell 脚本的新手。我正在尝试创建一个数组,其中字符串 x(截至目前我正在使用静态值进行测试)将在 运行 时间内由用户输入。

#!/bin/bash
x="101:Redmi:Mobile:15000#102:Samsung:TV:20000#103:OnePlus:Mobile:35000#104:HP:Laptop:65000#105:Samsung:Mobile:10000#106:Samsung:TV:30000"
i=0
index=0 
declare -a categ_array=()
declare  -a amnt_array=()
declare -a cnt_array=()
echo "$x"  | tr '#' '\n' | cut -d ":" -f 3-4 | while read -r line ;
do
  echo "------Inside while loop------"
  echo $line
  category=$(echo "$line" | cut -d ":" -f 1 )
  echo $category
  amount=$(echo "$line" | cut -d ":" -f 2 )
  echo $amount
  echo $i
  categ_array[$i]=${category}
  amnt_array[$i]=${amount}
  cnt_array[$i]=1
  let i+=1
  
done

echo Category:
for n in "${categ_array[@]}"
do
 echo $n
done ```      



When I run the above script, I do not get any output. Where as I want output as

``` categ_array should have data as (Mobile,TV,Mobile,Laptop,Mobile,TV) ```                                 
```amnt_array should have data as (15000,20000,35000,65000,10000,30000)```




Can someone tell me where am I going wrong?

根本问题是数组填充在管道内。管道阶段是 sub-processes 中的 运行,因此在主程序中对其中所做的变量所做的更改是不可见的。参见

由于数组是在管道的最后阶段填充的,如果您使用的是 运行ning Bash 4.2 版或更高版本,则可以通过将

shopt -s lastpipe

在管道之前的代码中。这导致管道的最后阶段在 top-level shell 中成为 运行,因此在管道完成后对变量的更改是可见的。

由于您使用的是 Bash,因此您可以在不使用管道(或 trcut 等外部命令)的情况下执行您想要的操作。试试这个 Shellcheck-干净的代码:

#! /bin/bash -p

x="101:Redmi:Mobile:15000#102:Samsung:TV:20000#103:OnePlus:Mobile:35000#104:HP:Laptop:65000#105:Samsung:Mobile:10000#106:Samsung:TV:30000"

declare -a categ_array=()
declare -a amnt_array=()
declare -a cnt_array=()

while IFS= read -r -d '#' line || [[ -n $line ]]; do
    IFS=: read -r _ _ category amount <<<"$line"

    categ_array+=( "$category" )
    amnt_array+=( "$amount" )
    cnt_array+=( 1 )
done <<<"$x"

echo Category:
for n in "${categ_array[@]}"; do
    echo "$n"
done