Courseiva
GNU and Unix CommandshardMultiple ChoiceObjective-mapped

LPIC-1 GNU and Unix Commands Practice Question

A script uses 'set -e' and then executes 'grep pattern file'. If the pattern is not found, the script exits. Which of the following modifications would prevent the script from exiting while still allowing detection of the pattern's absence?

⚠ Common exam trap

Test-takers frequently think '|| true' or piping to another command will both prevent exit and preserve the exit code, but they fail to realize that these constructs either discard the exit code or do not reliably prevent exit under all shell configurations.

Answer choices

Why each option matters

Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.

Correct answer & explanation

set +e; grep pattern file; exit_code=$?; set -e

It temporarily disables 'set -e' with 'set +e', runs the grep command, captures its exit code in a variable, then re-enables 'set -e'. This allows the script to continue executing after a non-zero exit from grep, while still preserving the exit code for later conditional checks. The other options either fail to preserve the exit code or do not prevent the script from exiting under 'set -e'.

Answer analysis

Option-by-option breakdown

For each option: why learners choose it and why it is or isn't the right answer here.

  • grep -q pattern file || true

    Why it's wrong here

    The '|| true' makes the command always succeed, hiding the failure.

  • set +e; grep pattern file; exit_code=$?; set -e

    Why this is correct

    Temporarily disables exit-on-error, captures exit code, then re-enables.

  • grep pattern file; exit_code=$?

    Why it's wrong here

    The script would exit on grep failure before the assignment to exit_code.

  • grep pattern file | head -1

    Why it's wrong here

    set -e still applies to the pipeline; if grep fails, the whole pipeline fails and exits.

About these practice questions

One of 527 original LPIC-1 practice questions on Courseiva, each with a full explanation and wrong-answer analysis — not exam dumps or protected exam content. Learn why practice questions differ from exam dumps →

How Courseiva writes practice questions · Editorial policy

JA

Written by Johnson Ajibi, MSc IT Security

Senior Network & Security Engineer · founder of Courseiva

This LPIC-1 practice question is part of Courseiva's free LPI certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the LPIC-1 exam.