snippetbashTip
if — Perform conditional processing in shell scripts. See also: `test`, `[`. More information: <https://w
Viewed 0 times
shellcommandconditionalperformcliprocessingscriptsif
Problem
How to use the
if command: Perform conditional processing in shell scripts. See also: test, [. More information: <https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs>.Solution
if — Perform conditional processing in shell scripts. See also: test, [. More information: <https://www.gnu.org/software/bash/manual/bash.html#Conditional-Constructs>.Execute the specified commands if the condition command's exit status is zero:
if {{condition_command}}; then {{echo "Condition is true"}}; fiExecute the specified commands if the condition command's exit status is not zero:
if ! {{condition_command}}; then {{echo "Condition is true"}}; fiExecute the first specified commands if the condition command's exit status is zero otherwise execute the second specified commands:
if {{condition_command}}; then {{echo "Condition is true"}}; else {{echo "Condition is false"}}; fiCheck whether a [f]ile exists:
if [[ -f {{path/to/file}} ]]; then {{echo "Condition is true"}}; fiCheck whether a [d]irectory exists:
if [[ -d {{path/to/directory}} ]]; then {{echo "Condition is true"}}; fiCheck whether a file or directory [e]xists:
if [[ -e {{path/to/file_or_directory}} ]]; then {{echo "Condition is true"}}; fiCheck whether a variable is defined:
if [[ -n "${{variable}}" ]]; then {{echo "Condition is true"}}; fiList all possible conditions (
test is an alias to [; both are commonly used with if):man testCode Snippets
Execute the specified commands if the condition command's exit status is zero
if {{condition_command}}; then {{echo "Condition is true"}}; fiExecute the specified commands if the condition command's exit status is not zero
if ! {{condition_command}}; then {{echo "Condition is true"}}; fiExecute the first specified commands if the condition command's exit status is zero otherwise execute the second specified commands
if {{condition_command}}; then {{echo "Condition is true"}}; else {{echo "Condition is false"}}; fiCheck whether a [f]ile exists
if [[ -f {{path/to/file}} ]]; then {{echo "Condition is true"}}; fiCheck whether a [d]irectory exists
if [[ -d {{path/to/directory}} ]]; then {{echo "Condition is true"}}; fiContext
tldr-pages: common/if
Revisions (0)
No revisions yet.