我目前正在使用bash编写一小段脚本。作为一个初学者,我找不到一个小问题的解决方案。 我需要做一个随着每次迭代而减少的计时,但是当它等于0时,它会回到10(10-> 0,然后是0-> 10)。我写了一小段目前无法使用的内容。
chrono=5
incremant=-1
while [ $chrono -ge 0 ];
do
echo $chrono
chrono=$((chrono+$incremant))
if [ $chrono -eq 1 ];
then
[ $incremant=1 ];
fi
done
我知道这是一个非常简单的问题,但我真的很坚持。在此先感谢您,祝您愉快。
答案 0 :(得分:1)
不确定为什么当bash
内置了非常好的类似于C的循环时,您在手动循环使事情变得复杂吗?
fn() {
echo $1
#printf "%2d * %2d = %3d\n" $chrono $chrono $((chrono * chrono))
}
for ((chrono=10; chrono > 0; chrono--)); do fn $chrono ; done
for ((chrono=1; chrono <= 10; chrono++)); do fn $chrono ; done
您可以根据自己的实际需要来更改循环部分,当前的部分包含10到1(含10),然后是1到10(含10),因此重复1
。例如,如果您不希望重复,只需将第二个循环的第一部分更改为chrono=2
。
您还可以使用fn
函数对值执行任意复杂操作(例如注释掉的位,它为您提供了格式良好的表达式列表,给出了每个表达式的平方数字,例如10 * 10 = 100
)。当前函数只是回显值:
10
9
8
7
6
5
4
3
2
1
1
2
3
4
5
6
7
8
9
10
答案 1 :(得分:0)
脚本:
#!/bin/bash
#Initial value
chrono=10
#Initial increment
increment=-1
#as long as the value of chrono is in the interval [0,10] do
while [[ "$chrono" -ge 0 && "$chrono" -le 10 ]];
do
#print the current value
echo $chrono
#change the value of chrono by adding the increment
chrono=$(( chrono+increment ))
#when the value of the chrono is at 1, change the sign of the increment to do the rebound
if [[ "$chrono" -eq 1 ]];
then
increment=1
fi
done
输出:
$ ./chrono.sh
10
9
8
7
6
5
4
3
2
1
2
3
4
5
6
7
8
9
10
要查看:
https://bash.cyberciti.biz/guide/Perform_arithmetic_operations http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html http://tldp.org/LDP/Bash-Beginners-Guide/html/chap_07.html https://www.gnu.org/software/bash/manual/html_node/Bash-Conditional-Expressions.html http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-7.html