Heinrich Schuchardt | a9122d2 | 2024-03-16 10:57:41 +0100 | [diff] [blame] | 1 | .. SPDX-License-Identifier: GPL-2.0-or-later |
| 2 | |
| 3 | .. index:: |
| 4 | single: if (command) |
| 5 | |
| 6 | if command |
| 7 | ========== |
| 8 | |
| 9 | Synopsis |
| 10 | -------- |
| 11 | |
| 12 | :: |
| 13 | |
| 14 | if <test statement> |
| 15 | then |
| 16 | <statements> |
| 17 | fi |
| 18 | |
| 19 | if <test statement> |
| 20 | then |
| 21 | <statements> |
| 22 | else |
| 23 | <statements> |
| 24 | fi |
| 25 | |
| 26 | Description |
| 27 | ----------- |
| 28 | |
| 29 | The if command is used to conditionally execute statements. |
| 30 | |
| 31 | test statement |
| 32 | Any command. The test statement set the $? variable. If the value of |
| 33 | $? becomes 0 (true) the statements after the **then** statement will |
| 34 | be executed. Otherwise the statements after the **else** statement. |
| 35 | |
Heinrich Schuchardt | d2fbe1f | 2024-03-22 08:57:31 +0100 | [diff] [blame] | 36 | Examples |
| 37 | -------- |
Heinrich Schuchardt | a9122d2 | 2024-03-16 10:57:41 +0100 | [diff] [blame] | 38 | |
| 39 | The examples shows how the value of a numeric variable can be tested with |
Heinrich Schuchardt | d2fbe1f | 2024-03-22 08:57:31 +0100 | [diff] [blame] | 40 | the :doc:`itest <itest>` command. |
Heinrich Schuchardt | a9122d2 | 2024-03-16 10:57:41 +0100 | [diff] [blame] | 41 | |
| 42 | :: |
| 43 | |
| 44 | => a=1; if itest $a == 0; then echo true; else echo false; fi |
| 45 | false |
| 46 | => a=0; if itest $a == 0; then echo true; else echo false; fi |
| 47 | true |
| 48 | |
| 49 | In the following example we try to load an EFI binary via TFTP. If loading |
| 50 | succeeds, the binary is executed. |
| 51 | |
| 52 | :: |
| 53 | |
| 54 | if tftp $kernel_addr_r shellriscv64.efi; then bootefi $kernel_addr_r; fi |
| 55 | |
| 56 | Return value |
| 57 | ------------ |
| 58 | |
| 59 | The value of $? is the return value of the last executed statement. |
| 60 | |
| 61 | :: |
| 62 | |
| 63 | => if true; then true; else true; fi; echo $? |
| 64 | 0 |
| 65 | => if false; then true; else true; fi; echo $? |
| 66 | 0 |
| 67 | => if false; then false; else false; fi; echo $? |
| 68 | 1 |
| 69 | => if true; then false; else false; fi; echo $? |
| 70 | 1 |
| 71 | => if false; then true; fi; echo $? |
| 72 | 1 |