如何使用 for 循环和 if 创建一个简单的程序。
我的代码:
for i in mon tue wed thurs fri sat
do
echo weekday: $i
if [ $i == thurs ]
then
echo weekend: $i+1
fi
done
和输出:
weekday: mon
weekday: tue
weekday: wed
weekday: thurs
weekend: thurs+1
weekday: fri
weekday: sat
但是,我想要这样的输出:
weekday: mon
weekday: tue
weekday: wed
weekday: thurs
weekend: fri
weekend: sat
我错过了哪种语法?
答案1
给定代码:
for i in mon tue wed thurs fri sat
do
echo weekday: $i
if [ $i == thurs ]
then
echo weekend: $i+1
fi
done
echo weekday: $i
每次迭代都会被调用- 循环
for
每次迭代都会生成一个元素到i
变量。i
不是您所期望的数组索引
获得预期输出的不同方法:
1)进行字符串比较
for i in mon tue wed thurs fri sat
do
if [ $i == fri ] || [ $i == sat ]
then
echo weekend: $i
else
echo weekday: $i
fi
done
2)使用字符串保存前缀,并根据条件进行修改
s='weekday'
for i in mon tue wed thurs fri sat
do
echo "$s: $i"
if [ $i == thurs ]
then
s='weekend'
fi
done
3)使用数组
days=(mon tue wed thurs fri sat)
for ((i=0; i<${#days[@]}; i++))
do
if (( i < 4 ))
then
echo "weekday: ${days[$i]}"
else
echo "weekend: ${days[$i]}"
fi
done