Home > Enterprise >  (Bash) In while loop, what's the difference of commands before 'do'?
(Bash) In while loop, what's the difference of commands before 'do'?

Time:08-11

I saw some people putting codes before 'do'.


Question 1:
What's the difference between two loops, function_1 and function_2?

a=1;b=1;c=1;d=1

function_1()
{
  while true
  ((a =1))
  ((b =1))
  do
    ((c =1))
    ((d =1))
    echo $a $b $c $d
    sleep 1
  done
}

function_2()
{
  while true
  do
    ((a =1))
    ((b =1))
    ((c =1))
    ((d =1))
    echo $a $b $c $d
    sleep 1
  done
}

Question 2:
What is do in loop command? Is it a command or a word delimiter? What does it do?

CodePudding user response:

What's the difference between two loops

They have different conditional and body commands lists.

The overall rule is that the exit status of almost anything in shell is the exit status of last command executed. The first loop executes a list of 3 commands

while
   true
   (( a  = 1 ))
   (( b  = 1 ))
do

while body executes if the exit status of the conditional list is zero. The exit status of the list of 3 commands is equal to the exit status of last command executed (( b = 1 )). The exit status of arithmetic expression ((....)) is zero, if the expression inside is equal to non-zero. The result of = operator is equal to the assigned value.

b starts with value 1, and then is added is = 1. When it will overflow, after ~2^64 iterations, b will come back to zero, in which case the arithmetic expression will exit with non-zero exit status, in which case the loop will terminate.

The second loop just executes true, which always exits with zero exit status.

What is do in loop command? What does it do?

Starts the body of the loop.

Is it a command or a word delimiter?

Technically, it's a reserved word.

CodePudding user response:

From the docs https://www.gnu.org/software/bash/manual/bash.html#Reserved-Words, 'do' is a reserved word in this case. It's acting as a delimiter.

The difference in your two examples is that function_1 has a loop condition of true ((a =1)) ((b =1)) whereas in function_2 the loop condition is just true. That is, function_1 is incrementing a and b as it determines whether to loop or not, whereas function_2 increments them within the loop itself. Significantly, function_1 loop condition true ((a =1)) ((b =1)) evaluates to the last expression ((b =1)) which causes it to loop.

The difference can be seen if you replace true with false, where the loop condition for function_1 becomes false ((a =1)) ((b =1)), which will always loop, whereas function_2 does not loop.

  • Related