2019-03-31 09:05:09 +00:00
.. _cmd-if:
2018-12-17 01:39:33 +00:00
if - conditionally execute a command
2019-01-03 04:10:47 +00:00
====================================
2018-12-17 01:39:33 +00:00
2018-12-18 01:58:24 +00:00
Synopsis
--------
2018-12-16 21:08:41 +00:00
if CONDITION; COMMANDS_TRUE...;
[else if CONDITION2; COMMANDS_TRUE2...;]
[else; COMMANDS_FALSE...;]
end
2018-12-18 01:58:24 +00:00
2018-12-16 21:08:41 +00:00
2018-12-19 02:44:30 +00:00
Description
2019-01-03 04:10:47 +00:00
-----------
2018-12-16 21:08:41 +00:00
2018-12-19 20:02:45 +00:00
`` if `` will execute the command `` CONDITION `` . If the condition's exit status is 0, the commands `` COMMANDS_TRUE `` will execute. If the exit status is not 0 and `` else `` is given, `` COMMANDS_FALSE `` will be executed.
2018-12-16 21:08:41 +00:00
2019-03-31 09:24:04 +00:00
You can use :ref: `and <cmd-and>` or :ref: `or <cmd-or>` in the condition. See the second example below.
2018-12-16 21:08:41 +00:00
2019-03-31 09:32:40 +00:00
The exit status of the last foreground command to exit can always be accessed using the :ref: `$status <variables-status>` variable.
2018-12-16 21:08:41 +00:00
2018-12-19 02:44:30 +00:00
Example
2019-01-03 04:10:47 +00:00
-------
2018-12-16 21:08:41 +00:00
2018-12-19 20:02:45 +00:00
The following code will print `` foo.txt exists `` if the file foo.txt exists and is a regular file, otherwise it will print `` bar.txt exists `` if the file bar.txt exists and is a regular file, otherwise it will print `` foo.txt and bar.txt do not exist `` .
2018-12-16 21:08:41 +00:00
2018-12-19 03:14:04 +00:00
::
if test -f foo.txt
echo foo.txt exists
else if test -f bar.txt
echo bar.txt exists
else
echo foo.txt and bar.txt do not exist
end
2018-12-16 21:08:41 +00:00
The following code will print "foo.txt exists and is readable" if foo.txt is a regular file and readable
2018-12-19 03:14:04 +00:00
::
if test -f foo.txt
and test -r foo.txt
echo "foo.txt exists and is readable"
end