Run a task only when grep finds enabled in config.ini.
Use grep's exit status directly as the if condition.
Which statement is appropriate?
if evaluates the exit status of its condition command; grep -q suppresses output and reports whether it matched.
Detailed explanation
if [ grep -q enabled config.ini ]; then run_job; fiIncorrect. [ is a test command and does not execute grep nested inside it.
Incorrect. [ is a test command and does not execute grep nested inside it.
if $(grep -q enabled config.ini); then run_job; fiIncorrect. Command substitution would try to execute grep's empty output as a command.
Incorrect. Command substitution would try to execute grep's empty output as a command.
if $? grep -q enabled config.ini; then run_job; fiIncorrect. This is not a valid command-and-condition sequence.
Incorrect. This is not a valid command-and-condition sequence.
if grep -q enabled config.ini; then run_job; fiCorrect. if evaluates grep -q's success status and runs the then branch on a match.
Correct. if evaluates grep -q's success status and runs the then branch on a match.
Try it yourself
An example you can run in a temporary verification environment.
file=$(mktemp); printf '%s\n' enabled > "$file"; if grep -q enabled "$file"; then printf match; fi; rm -f -- "$file"Expected result
matchKey points
- if evaluates exit status
- grep -q is quiet
- [ is the test command
Notes
- Environment: GNU Bash 5.2 / GNU grep / 一時ファイル
- 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.