Write a Bash Command That Fails Randomly
Janne Kemppainen |Usually you want the commands that you run to succeed. Though sometimes it might be useful to make them fail randomly for test purposes.
When you run a command on the command line it will return an exit code when it finishes. Zero is interpreted as a successful execution, and any non-zero exit code is an error. After all, there can be many different ways that a program fails.
To make a command work and fail randomly we need to make it return zero and non-zero values in a random manner.
The $RANDOM
variable returns a random integer between 0 and 32767. We can use the modulo operator %
to convert the value to 0 or 1. This return statement works directly on the command line or in a sourced function:
>> return $((RANDOM % 2))
>> echo $?
0
The $?
is a special syntax for accessing the return code of the previous command. If you run these commands multiple times you’ll see that the echoed value changes between zero and one. This is a command that fails 50% of the time!
Sometimes using return
might not work. In this case you can try to use exit
instead:
>> exit $((RANDOM % 2))
Note that this will also exit your terminal when it is run as a plain command.
The $(( calculations ))
syntax is called Arithmetic Expansion, and it is a built-in feature in Bash. You can use it to perform mathematical operations such as the modulo calculation we are doing here. The result is returned back to the outer scope.
Could you make the command fail more or less frequently? Try if you can find a solution!
Previous post
Run Selected Python Unit Tests from the Command Line