Bash memo for (if statement and test command)
- The if statement determines the exit status of the command specified in the conditional expression and branches. True if the exit status is 0, false otherwise
[ "A" = "A"]If there is no space between  like this, an error will occur. For example
["A" = "A"], it is an error to write. It is easy to understand if [ is a command
<,>,<=,>=cannot be used in conditional expressions. You can use
-lt(<),-gt(>),-le(<=),-ge(>=)instead. -lt (less than), -gt (greater than), -le (less than or equal), -ge (greater than or equal), respectively. But it’s hard to understand, so I wrote it all down.
- If you have any trouble , just use man
All you can find in this repo
GitHub - spy86/bash_if_statement_and_test_command
You can't perform that action at this time. You signed in with another tab or window. You signed out in another tab or…
- Are the strings equal?
- Use > as a conditional expression → Use -gt (greater than)
- Use < in a conditional expression → Use -lt (less than)
- Use >= in a conditional expression →Use -ge (greater than or equal)
- Use <= in the conditional expression → Use -le (less than equal)
- Check the existence of a directory → Use the -d option.
- Check the existence of a file → use the -f option
- Determine whether the command executed in the shell script ended normally → After executing
$?the command, you can get the exit status code of the previous command by , so judge 0 (whether it ended normally).
$?stores only the exit status code of the previous command, so if you want to execute another command between the command you want to judge and the if statement, store the contents of
- Use the NOT condition → Use the ! option.
- Using AND and OR conditions → When using -a and -o
- Using AND and OR conditions → When using && and ||
⚠️It can be written with -a (AND condition) and -o (OR condition) of the test command, but && (AND condition) and || (OR condition) are easier to understand personally. However, while -a and -o determine the condition with one test command, && and || determine the exit status code and execute subsequent processing, so note that the writing style is slightly different.
by the author.