Bash memo for (if statement and test command)

Maciej
2 min readAug 8, 2022

--

Photo by Waldemar Brandt on Unsplash

Prerequisite knowledge

  • 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

Command collection

All you can find in this repo

  1. Are the strings equal?
  2. Use > as a conditional expression → Use -gt (greater than)
  3. Use < in a conditional expression → Use -lt (less than)
  4. Use >= in a conditional expression →Use -ge (greater than or equal)
  5. Use <= in the conditional expression → Use -le (less than equal)
  6. Check the existence of a directory → Use the -d option.
  7. Check the existence of a file → use the -f option
  8. 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 $?
  9. Use the NOT condition → Use the ! option.
  10. Using AND and OR conditions → When using -a and -o
  11. 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.

https://giphy.com/

--

--

Maciej

DevOps Consultant. I’m strongly focused on automation, security, and reliability.