简体   繁体   中英

for loop / if condition in shell script

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 eg every 5000 the actual index.

$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

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.sh 5000 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.

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

counter=0

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

if [ $i -eq $counter ]

Line 5 should be: (Double parentheses)

counter=$((counter+1000))

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM