我写了一个示例脚本,它将字符串拆分为多个变量
#!/bin/bash
IN="One-XX-X-17.0.0"
IFS='-' read -a ADDR <<< "$IN"
for i in "${ADDR[@]}"; do
echo "${ADDR[i]}"
done
while IFS='.' read -a ADDR[3]; do
for i in "${ADDR[3]}"; do
process "$i"
done
如var11 = 1,var12 = XX,var13 = X,major1 = 17,minor1 = 0,rel1 = 0
但每次运行此脚本时都会收到错误。 有人能告诉我我的剧本有什么问题
答案 0 :(得分:1)
#!/bin/bash
IN="One-XX-X-17.0.0"
IFS='-' read -a ADDR <<< "$IN"
for i in "${ADDR[@]}"; do
echo "$i"
done
#split 17.0.0 into NUM
IFS='.' read -a NUM <<<${ADDR[3]};
for i in "${NUM[@]}"; do
echo "$i"
done
输出:
One
XX
X
17.0.0
17
0
0
<强> UPD 强>
#same code
#array of names of variable
var=(major minor rel)
#split 17.0.0 into NUM
IFS='.' read -a NUM <<<${ADDR[3]};
for((i=0;i<${#NUM[@]};i++)); do
#assign
eval ${var[$i]}=${NUM[$i]}
done
#now test
echo $major
echo $minor
echo $rel
输出:
17
0
0