tldr/pages/common/if.md

38 lines
1.3 KiB
Markdown
Raw Permalink Normal View History

2016-01-05 18:47:12 +00:00
# if
2021-12-26 04:30:57 +00:00
> Performs conditional processing in shell scripts.
2021-03-08 20:06:24 +00:00
> See also: `test`, `[`.
2021-12-26 04:30:57 +00:00
> More information: <https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs>.
2016-01-05 18:47:12 +00:00
2021-12-26 04:30:57 +00:00
- Execute the specified commands if the condition command's exit status is zero:
2016-01-05 18:47:12 +00:00
2021-12-26 04:30:57 +00:00
`if {{condition_command}}; then {{echo "Condition is true"}}; fi`
2016-01-05 18:47:12 +00:00
2021-12-26 04:30:57 +00:00
- Execute the specified commands if the condition command's exit status is not zero:
2016-01-05 18:47:12 +00:00
2021-12-26 04:30:57 +00:00
`if ! {{condition_command}}; then {{echo "Condition is true"}}; fi`
2021-12-26 04:30:57 +00:00
- Execute the first specified commands if the condition command's exit status is zero otherwise execute the second specified commands:
2021-12-26 04:30:57 +00:00
`if {{condition_command}}; then {{echo "Condition is true"}}; else {{echo "Condition is false"}}; fi`
2021-12-26 04:30:57 +00:00
- Check whether a [f]ile exists:
2021-12-26 04:30:57 +00:00
`if [[ -f {{path/to/file}} ]]; then {{echo "Condition is true"}}; fi`
2021-12-26 04:30:57 +00:00
- Check whether a [d]irectory exists:
2021-12-26 04:30:57 +00:00
`if [[ -d {{path/to/directory}} ]]; then {{echo "Condition is true"}}; fi`
- Check whether a file or directory [e]xists:
`if [[ -e {{path/to/file_or_directory}} ]]; then {{echo "Condition is true"}}; fi`
- Check whether a variable is defined:
`if [[ -n "${{variable}}" ]]; then {{echo "Condition is true"}}; fi`
2021-03-08 20:06:24 +00:00
- List all possible conditions (`test` is an alias to `[`; both are commonly used with `if`):
2021-03-08 20:06:24 +00:00
`man [`