bash shell脚本中的for循环/if条件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3422827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:33:05  来源:igfitidea点击:

for loop / if condition in shell script

bashshell

提问by mkn

I've never done shell script before and now I'm running into a simple problem... I have a for loop which executes every time the run.sh script. To see how far the script has already run I want to print e.g. every 5000 the actual index.

我以前从未做过 shell 脚本,现在我遇到了一个简单的问题......我有一个 for 循环,每次 run.sh 脚本时都会执行。要查看脚本已经运行了多远,我想打印例如每 5000 个实际索引。

$counter = 0
for ((  i = 0 ;  i <= 5000;  i++  ))do
    if ($i =  $counter); then
            echo "$counter"
            counter=$(counter+1000)
    fi
./run.sh
done

running this piece of code gives me the following error

运行这段代码给了我以下错误

./for_loop.sh: line 1: =: command not found
./for_loop.sh: line 3: 0: command not found

I have also tried to init the variable counter with

我也尝试用初始化变量计数器

declare -i counter = 0

which gives me the following error

这给了我以下错误

./for_loop.sh: line 1: declare: `=': not a valid identifier

回答by Derek Mahar

You don't really need two counters. A single counter will suffice:

你真的不需要两个计数器。一个计数器就足够了:

for (( counter = 0; counter <= 5000; counter++ ))
do
    if (( counter % 1000 == 0 ))
    then
            echo "$(( counter / 1000 ))"
    fi
    ./run.sh
done

This executes run.sh5000 times and prints the counter value every 1000 iterations. Note that %is the modulus operator which computes remainder after division and /is the integer division operator.

这将执行run.sh5000 次并每 1000 次迭代打印计数器值。请注意,这%是计算除法后余数的模运算符,并且/是整数除法运算符。

回答by schot

Line 1 should be: (No $, no extra spaces around '=')

第 1 行应该是:(没有 $,'=' 周围没有多余的空格)

counter=0

Line 3 should be: (Square brackets, '-eq' because '=' is for string equality)

第 3 行应该是:(方括号,'-eq' 因为 '=' 用于字符串相等)

if [ $i -eq $counter ]

Line 5 should be: (Double parentheses)

第 5 行应该是:(双括号)

counter=$((counter+1000))

回答by Jed Schneider

In line 3 I believe you have mistaken assignment =for equality ==

在第 3 行中,我相信您将分配错误地视为=平等==

http://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic

http://www.gnu.org/software/bash/manual/bashref.html#Shell-Arithmetic