What's the purpose of "true" in bash "if sudo true; then"
true
in bash isn't a keyword, it's a program that instantly exits with a successful exit code.
Likewise, false
is a program that exits with an unsuccessful exit code.
You can try this out by running both programs from your terminal, and then reading the $?
variable, which contains the exit code of the last program;
true
echo $? # 0
false
echo $? #1
if sudo true
isn't equivalent to if sudo == true
. if sudo true
is running the true
program using sudo
, and checking the exit code.
Therefore:
if sudo false; then
is running the program false
as sudo. The return will always be false.
if sudo true == false
will run the program true
with the arguments ==
and false
using sudo
. This obviously isn't want you intended.
if [!(sudo true)]
is invalid syntax.
What you are probably looking for is
if ! sudo true;
I feel like the accepted answer didn't actually answer your question?
The purpose of doing this is to check that you can actually sudo
.
How this check is performed is via the true
program as explained in the accepted answer.
As I see in this script. It is just checking if sudo is enabled, that is it..
true just returns true.
So in this case if they need to run any command with sudo it checks at start first, asking the password only one time.
The condition works like this: if sudo are executing the true command correctly, it will return true for the if condition, then sudo is enabled and the user typed the password correctly, else you typed the password wrong or sudo is not enabled, the script must not continue.
The other commands do not need to ask sudo password, because your authentication are sucessfully in first time (but this depends on the sudo configuration, so this scripts depends much in the environment configuration)
The 'echo password ok' demonstrate that too. the shell script will not ask the password anymore.