tldr/pages/common/if.md

30 lines
847 B
Markdown
Raw Normal View History

2016-01-05 18:47:12 +00:00
# if
2016-01-13 11:04:46 +00:00
> Simple shell conditional.
2021-03-08 20:06:24 +00:00
> See also: `test`, `[`.
> More information: <https://www.tcl.tk/man/tcl8.6.11/TclCmd/if.html>.
2016-01-05 18:47:12 +00:00
2021-03-08 20:06:24 +00:00
- Execute two different commands based on a condition:
2016-01-05 18:47:12 +00:00
2021-03-08 20:06:24 +00:00
`if {{command}}; then {{echo "true"}}; else {{echo "false"}}; fi`
2016-01-05 18:47:12 +00:00
2021-03-08 20:06:24 +00:00
- Check if a variable is defined:
2016-01-05 18:47:12 +00:00
2021-03-08 20:06:24 +00:00
`if [[ -n "{{$VARIABLE}}" ]]; then {{echo "defined"}}; else {{echo "not defined"}}; fi`
2021-03-08 20:06:24 +00:00
- Check if a file exists:
2021-03-08 20:06:24 +00:00
`if [[ -f "{{path/to/file}}" ]]; then {{echo "true"}}; else {{echo "false"}}; fi`
2021-03-08 20:06:24 +00:00
- Check if a directory exists:
2021-03-08 20:06:24 +00:00
`if [[ -d "{{path/to/directory}}" ]]; then {{echo "true"}}; else {{echo "false"}}; fi`
2021-03-08 20:06:24 +00:00
- Check if a file or directory exists:
2021-03-08 20:06:24 +00:00
`if [[ -e "{{path/to/file_or_directory}}" ]]; then {{echo "true"}}; else {{echo "false"}}; 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 [`