true is a shell builtin, not a keyword. it is technically a command that does only one thing: it exits with a status code of 0.
[root@oel01db ~]# type -a true
true is a shell builtin
true is /usr/bin/trueYou can use true anywhere you would use a command, which makes it perfect for infinite loops in scripts.
Example of true (The Builtin) in a loop:
while true; do
echo "Script is still alive until you crl + C.."
sleep 3
done[root@oel01db Shell-Scripting]# while true; do
> echo "Script is still alive until you crl + C.."
> sleep 3
> done
Script is still alive until you crl + C..
Script is still alive until you crl + C..
Script is still alive until you crl + C..
^C
[root@oel01db Shell-Scripting]#
In this case, while is the keyword (providing the structure), and true is the builtin command (providing the success exit code to keep the loop going).
## true vs. : (The Null Command)
In Bash, there is a "secret" version of true which is just a colon :. It is also a builtin and does the exact same thing:
[root@oel01db ~]# type :
: is a shell builtin
[root@oel01db ~]# :
[root@oel01db ~]# echo $?
0
[root@oel01db Shell-Scripting]# while : ; do> echo "Script is still alive until you crl + C.."
> sleep 3
> done
Script is still alive until you crl + C..
Script is still alive until you crl + C..
^C
[root@oel01db Shell-Scripting]#
Sysadmins often use : instead of true because it's slightly faster to type and is technically a "no-op" (no operation).
The false command
The false command is the exact opposite of the true command. Its sole purpose in life is to do nothing and exit with a non-zero exit status (usually 1).
[root@oel01db ~]# false
[root@oel01db ~]# echo $? 1
.1
[root@oel01db ~]#
A. Creating Infinite Loops (that you stop manually)
While while true runs forever, until false does the same thing (it runs until the condition becomes "true", but false is always "false").
until false; do
echo "Script is still alive until you crl + C.."
sleep 3
done
[root@oel01db Shell-Scripting]# until false; do
> echo "Script is still alive until you crl + C.."
> sleep 3
> done
Script is still alive until you crl + C..
Script is still alive until you crl + C..
^C
[root@oel01db Shell-Scripting]#
No comments:
Post a Comment