Linux command
if 命令
文本
涉及管道、覆盖或删除,执行前请先确认路径和参数。
常用示例
Basic if statement
if [[ condition ]]; then command; fi
If-else
if [[ -f file ]]; then echo "exists"; else echo "missing"; fi
If-elif-else
if [[ $x -eq 1 ]]; then cmd1; elif [[ $x -eq 2 ]]; then cmd2; else cmd3; fi
Test file exists
if [[ -e file ]]; then echo "found"; fi
Test string equality
if [[ "$a" == "$b" ]]; then echo "equal"; fi
Test command exit status
if grep -q "pattern" file; then echo "found"; fi
Numeric comparison
if [[ $count -gt 10 ]]; then echo "more than 10"; fi
说明
if is a shell builtin conditional statement. It executes the _test-commands_ list and, if the exit status is zero (success), runs the corresponding then clause. If non-zero, each elif clause is tested in turn. If no condition succeeds and an else clause is present, its commands are executed. Although if is most commonly used with test or [ ] expressions, any command can serve as the condition since the decision is based on exit status. For example, if grep -q pattern file branches on whether grep found a match.
参数
- then
- Introduces commands to execute when the preceding condition is true.
- elif
- Else-if clause; tests an additional condition if prior conditions were false.
- else
- Commands to execute if all preceding conditions were false.
- fi
- End of the if block.
FAQ
What is the if command used for?
if is a shell builtin conditional statement. It executes the _test-commands_ list and, if the exit status is zero (success), runs the corresponding then clause. If non-zero, each elif clause is tested in turn. If no condition succeeds and an else clause is present, its commands are executed. Although if is most commonly used with test or [ ] expressions, any command can serve as the condition since the decision is based on exit status. For example, if grep -q pattern file branches on whether grep found a match.
How do I run a basic if example?
Run `if [[ condition ]]; then command; fi` in a terminal, then adjust file names, paths, flags, or remote targets for your system.
What does then do in if?
Introduces commands to execute when the preceding condition is true.