- [Instructor] Running a command until it succeeds.
In the previous video, we have learned about
reading end characters without pressing the return key.
In this video, we'll learn how to run
a command repeatedly until it succeeds.
When using your shell for everyday tasks,
there will be some cases where a command
might succeed only after some conditions are met,
or the operation depends on an external event,
such as a file being available to download.
In such cases, one might want to run
a command repeatedly until it succeeds.
Define a function in this way.
Or add this to your shell's RC file for ease of use.
Now we'll see how the function works.
We create a function called repeat
that has an infinite while loop,
which attempts to run the command past as a parameter,
accessed by $@, to the function.
It then returns if the command was successful,
thereby exiting the loop.
We saw a basic way to run commands until they succeed.
Let's see what we can do to make things more efficient.
A faster approach.
On most modern systems, true is implemented as
a binary end-slash bid.
This means that each time the aforementioned
while loop runs, the show has to spawn a process.
To avoid this, we can use the code on shell built in,
which always returns exit code zero.
Though not as readable, this is certainly
faster than the first approach.
Adding a delay.
Let's say you're using repeat to download a file
from the internet, which is not available right now,
but will be after some time.
An example would be
in the current form, we'll be sending too much traffic
to the web serial at www.example.com,
which causes problems to the server
and maybe even to you if, say,
the server blacklists your IP for spam.
To solve this, we can modify the function
and add a small delay, like this.
This will cause the command to run every 30 seconds.
Awesome.
We have successfully run a command until it succeeds.
In the next video, we'll learn about
field separators and iterators.