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?
>Solution :
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.