Print ready only if check_ready succeeds.
Use the command's exit status directly as the if condition.
Which form is appropriate?
if COMMAND; then ...; fi runs the then branch when COMMAND returns status 0; there is no need to compare $? separately.
Detailed explanation
if $? check_ready; then echo ready; fiIncorrect. $? is not placed before a command as an if condition.
Incorrect. $? is not placed before a command as an if condition.
if echo ready; then check_ready; fiIncorrect. It tests echo first and runs check_ready in the wrong order.
Incorrect. It tests echo first and runs check_ready in the wrong order.
if check_ready; then echo ready; fiCorrect. The then branch runs when check_ready succeeds.
Correct. The then branch runs when check_ready succeeds.
if check_ready; do echo ready; doneIncorrect. if uses then and fi, not do and done.
Incorrect. if uses then and fi, not do and done.
Try it yourself
An example you can run in a temporary verification environment.
sh -c 'check_ready() { return 0; }; if check_ready; then echo ready; fi'Expected result
readyKey points
- if tests a command status
- 0 selects then
- Place the condition command directly
Notes
- Environment: POSIX sh / 一時関数
- Command output formatting can vary slightly by distribution or tool version.
- Run the example in a temporary directory or process when possible.
Foundation review
Read the scope first
Check whether the command acts on the current shell, a new process, an existing process, or a file.
Verify the observable result
Use the supplied command and compare the output with the expected result.