Back to Fish

if - conditionally execute a command¶

site/docs/4.1/cmds/if.html

latest2.0 KB
Original Source

if - conditionally execute a command

Synopsis

if CONDITION; COMMANDS\_TRUE ...;[else if CONDITION2; COMMANDS\_TRUE2 ...;][else; COMMANDS\_FALSE ...;]end

Description

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.

You can use and or or in the condition. See the second example below.

The exit status of the last foreground command to exit can always be accessed using the $status variable.

The -h or --help option displays help about using this command.

Example

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.

if test -f foo.txtecho foo.txt existselse if test -f bar.txtecho bar.txt existselseecho foo.txt and bar.txt do not existend

The following code will print “foo.txt exists and is readable” if foo.txt is a regular file and readable

if test -f foo.txtand test -r foo.txtecho "foo.txt exists and is readable"end

See also

if is only as useful as the command used as the condition.

Fish ships a few: