我是 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?
uj5u.com熱心網友回復:
根本問題是陣列填充在管道內。流水線階段在子行程中運行,因此在子行程中對變數所做的更改在主程式中不可見。請參閱讀入管道中的變數時會發生什么?.
由于陣列是在管道的最后階段填充的,因此如果您正在運行 Bash 4.2 或更高版本,則可以通過將
shopt -s lastpipe
在管道之前的代碼中。這會導致管道的最后階段在頂級 shell 中運行,因此在管道完成后對變數的更改是可見的。
tr由于您使用的是 Bash,因此您無需使用管道(或外部命令,如and )就可以做您想做的事cut。試試這個Shellcheck -clean 代碼:
#! /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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/425663.html
上一篇:使用unixsed替換js路徑
