我必须编写一个脚本来读取一个数字并将其倒数到 0。
我不断收到此错误:
practice123.sh: line 10: let: 1=[: attempted assignment to non-variable (error token is "=[")
我似乎无法让循环正确倒计时。我正在使用 shell 检查,并且我的语法看起来不错。任何意见将不胜感激。
#!bin/bash
# This script will take one number from the CLI and see if the argument given is a valid variable. Then it will count that variable down to 0.
var1=var1
echo "Enter a number."
read var1
until [ "$var1" -le 0 ]
do
echo "$var1"
let $var1=[ $var1 -1 ]
done
答案1
算术表达式使用双括号,而不是方括号:
(( var1 = var1 - 1 ))
或更短
(( var1 -= 1 ))
(( var1-- ))
(( --var1 ))
let
您也可以使用:
let var1=var1-1
let var1--
let --var1
let 'var1 = var1 - 1' # Quotes needed for whitespace.
您还可以使用算术扩展(但为什么?)
var1=$(( var1 - 1 ))
答案2
#!/bin/bash
# linux countdown script
echo "countdown loading....."
sleep 2
echo "Enter value below"
read number
countdown=$number
until [ $countdown -le "0" ];
do
echo "$countdown"
(( countdown -= 1 ))
if [ $countdown ];
then
sleep 1
fi
done
echo "countdown completed"