我创建了动态变量。
for (( c=1; c<=2; c++ ))
do
eval "prev$c=$number";
done
prev1
,prev2
for (( c=1; c<=2; c++ ))
do
eval "current$c=$number";
done
current1
,current2
如果我有变量
$prev1
是1
$prev2
是2
$current1
是1
$current2
3
如何在循环内与 if 进行比较?以下是错误的,有人可以纠正语法吗?提前致谢。
for (( c=1; c<=2; c++ ))
do
if ((prev$i != current$i)); then
echo "prev$i is $prev[i] and current$i is $current[i], they are different"
fi
done
答案1
在bash中,您可以使用变量间接寻址
prev=prev$c
current=current$c
if ((${!prev} != ${!current})); then
echo "prev$c is ${!prev} and current$c is ${!current}, they are different"
fi
但使用数组更安全(无需评估):
#! /bin/bash
number=0
for (( c=1; c<=2; c++ )) ; do
prev[c]=$number
number=$c
current[c]=$number
if ((${prev[c]} != ${current[c]})); then
echo "prev$c is ${prev[c]} and current$c is ${current[c]}, they are different"
fi
done