Linux Scripting Interview Questions on Inputs and Failures

Linux scripting interview answers should explain what a script accepts, what it produces and what happens when something goes wrong. Be ready to discuss input validation, partial completion, repeat runs, tests and review. The questions below use an offline Python example that creates a proposed retention plan from invented CSV data.

Aug 28, 2024 - 12:43
Updated: 
102.4k

Linux Administration in IT Infrastructure · Interview preparation

Linux Scripting Interview Questions on Inputs and Failures

Quick answer: Linux scripting interview answers should explain what a script accepts, what it produces and what happens when something goes wrong. Be ready to discuss input validation, partial completion, repeat runs, tests and review. The questions below use an offline Python example that creates a proposed retention plan from invented CSV data. It changes no files or settings, so you can examine the failure behaviour before discussing a real maintenance job.

Key takeaways

  • State the input format and allowed values before describing the loop.
  • Validate the complete batch before returning a proposed plan.
  • Keep validation, permission to act and execution as separate decisions.
  • Explain how repeat runs and partial failures affect the intended task.
  • Bring a small example whose successful and rejected outputs you understand.

Table of Contents

Which language would you choose for this task?

For a short job that coordinates existing Linux utilities, a shell script may be enough. For structured records, several validation rules and clear error messages, Python can make the logic easier to inspect. Explain the task that drove your choice, including the runtime available on the intended machines.

In this interview exercise, a maintenance team supplies labels and proposed retention periods. We choose Python because its CSV module handles tabular records without splitting every line at commas. Quoted CSV fields can themselves contain commas, so a hand-written split is a poor substitute.

A useful answer also names what the script will not decide. A syntactically valid retention period does not establish that deleting records after that period is permitted. The owner still needs to approve the policy and any exceptions.

What input contract would you agree before writing code?

Specify the column names, whether their order matters, permitted values, duplicate handling and the meaning of an empty file. Our deliberately narrow format requires exactly label and retention_days, in that order. Labels must be nonempty and unique; days must be ASCII decimal digits representing an integer from 1 through 365.

Those bounds belong to this invented exercise, not to a universal retention standard. Ask the interviewer whether the real system permits an indefinite hold or a zero-day category before extending the format. Keep unusual cases explicit instead of interpreting an unknown value as permission to proceed.

The example uses StringIO from Python’s stream library to supply text in memory. It does not read an operational inventory or open any log files.

Supplied valueExercise decisionReason
30Accept for reviewWhole number within the agreed range
7.5Reject the batchFractional days are outside this format
Two copies of web-aReject the batchDuplicate labels could create conflicting instructions

How does the example avoid returning a partial plan?

The function accumulates a local list and returns it only after every row passes. If the second record is invalid, the caller receives an exception instead of the already validated first record. The Python exception reference explains the ValueError used here for an unsuitable supplied value.

Read the two final lines before running the example: one input is accepted for review and the other is rejected. The rejection deliberately identifies the row and rule without echoing arbitrary record contents into an error message. This exact code was executed offline with the recorded expected output.

import csv
from io import StringIO


def review_plan(text):
    reader = csv.DictReader(StringIO(text))
    if reader.fieldnames != ["label", "retention_days"]:
        raise ValueError("unexpected columns")
    plan = []
    seen = set()
    for row_number, row in enumerate(reader, start=2):
        if None in row or None in row.values():
            raise ValueError(f"row {row_number}: wrong field count")
        label = row["label"].strip()
        days = row["retention_days"].strip()
        if not label or label in seen:
            raise ValueError(f"row {row_number}: empty or duplicate label")
        if not days.isascii() or not days.isdecimal() or not 1 <= int(days) <= 365:
            raise ValueError(f"row {row_number}: days must be 1..365")
        seen.add(label)
        plan.append((label, int(days)))
    if not plan:
        raise ValueError("no data rows")
    return plan


valid = "label,retention_days\nweb-a,7\nworker-b,30\n"
invalid = "label,retention_days\nweb-a,7\nworker-b,7.5\n"
for name, supplied in [("valid", valid), ("invalid", invalid)]:
    try:
        plan = review_plan(supplied)
    except ValueError as error:
        print(f"{name}: REJECTED ({error}); no plan returned")
    else:
        print(f"{name}: review plan {plan}; no changes performed")

Checked output:

valid: review plan [('web-a', 7), ('worker-b', 30)]; no changes performed
invalid: REJECTED (row 3: days must be 1..365); no plan returned

Would you stop the whole job or continue after an error?

That depends on the operation and the agreed failure policy. A malformed policy batch should fail before any operational change starts. A read-only report may instead collect invalid rows in a separate review file, provided the report clearly identifies what was excluded.

For a real multi-machine change, validation success is only the beginning. You need a record of which targets were attempted, which completed and which remain uncertain. An unavailable host is not a successful host. Stop conditions should follow the risk and recovery plan, rather than an arbitrary retry count.

Avoid catching every exception and printing success. Unexpected programming errors should remain visible. Give a concrete answer such as: “I would reject this complete input batch, ask for a corrected file, and retain the original submission reference for review.”

How would you explain idempotence and a dry run?

Idempotence concerns the resulting state after repeating an operation with the same intended inputs. Printing the same proposed plan twice is repeatable reporting; it does not prove a later maintenance action is idempotent. A script that appends a second entry every time can still exit successfully while producing the wrong state.

With Ansible, the check-mode guide describes simulation and module support limits. Tasks can also override check-mode behaviour, so inspect the actual playbook rather than assuming a flag makes arbitrary code harmless. The playbook guide explains desired state and notes that not every module or playbook behaves idempotently.

For this parser, a useful follow-up is whether a changed policy file should create a new review version. Do not silently reuse an approval for different input.

Which tests would you describe to the interviewer?

Start with examples tied to the contract: accepted boundaries of 1 and 365 days, a missing value, an extra field, an empty batch and duplicate labels. Include a valid first row followed by an invalid second row, because that catches accidental partial-plan returns.

Python’s unit-testing library can check expected return values and expected exceptions. These tests establish the parser’s behaviour for specified inputs. They do not establish the correctness of the organisation’s retention policy or the safety of a separate execution program.

Test questionExpected answer cue
What happens at 366 days?Reject before returning a plan
What if the header is misspelled?Report an unexpected format
What if an approved label changes?Require a fresh review of the changed input
What if the process stops midway through execution?Reconcile recorded target outcomes before retrying

What would you show in a script review?

Show the input contract, a short diff, checked examples and the boundary between reporting and acting. Explain dependencies, execution identity and how diagnostics avoid exposing secrets. The Git diff reference helps distinguish a working-tree comparison from a staged comparison; name the comparison you actually reviewed.

If asked for a real work example, describe only what you personally wrote or checked. A lab parser is valid evidence when labelled accurately. You can say that it rejected an invalid batch before returning any plan, then explain the extra approvals and execution tracking a production task would need.

Finish with a question for the interviewer: who owns the policy and who accepts a completed run? That answer determines the script’s responsibilities and the evidence it must preserve.

Related reading: Linux command semantics interview questions; Linux questions for DevOps delivery.

References

Frequently Asked Questions

Bash suits many utility-driven tasks, while structured data and extensive validation may be clearer in Python or another supported language.

No, validation establishes conformity with the input contract; approval depends on the owner, policy, target scope and change process.

Duplicate labels could assign conflicting periods to one target, so this exercise rejects the entire batch before returning a plan.

The example only parses invented text and prints a proposed review plan; it does not access files or perform retention actions.

The exercise contract accepts whole ASCII decimal days only, so a fractional value requires a policy decision and format change.

Check-mode support and task-level overrides matter, so inspect the modules and playbook before relying on its behaviour for safety.

Put a valid record before an invalid record and verify that the function raises an error without returning a partial plan.

Yes, explain the lab scope, show checked inputs and outputs, and distinguish those results from experience operating production systems.

What's Your Reaction?

Like Like 0
Dislike Dislike 0
Love Love 0
Funny Funny 0
Wow Wow 0
Sad Sad 0
Angry Angry 0
Anjali

I am passionate about technology, invention and big challenging tasks on my to- do list. In terms of the work I am doing also at Bunnyshell, I am most passionate about the technologies that we are using., I'm devoted to delivering content that not only informs but also inspires. Whether you need in- depth analysis pieces, educational attendants, or study- provoking opinion pieces, I draft content that resonates with tech suckers and professionals likewise.