Interview questions › Scripting (Bash, Groovy)

Scripting (Bash, Groovy) interview questions & answers

100 Scripting (Bash, Groovy) interview questions. Each links to a full answer page with a concise spoken answer, a technical explanation, and a hands-on example.

Tip: paste the job description + your resume into our free resume checker to see which of these skills the role actually requires.

All questions

  1. What is the purpose of the shebang line, and what does #!/bin/bash do? [Basic]
    The shebang tells the operating system which interpreter should run the script when it is executed directly.
  2. What is the difference between sh and bash? [Basic]
    sh is a POSIX-style shell interface, while bash is GNU Bash with additional features such as arrays, [[ ]], brace expansion, process substitution, and richer…
  3. How do you make a script executable and run it? [Basic]
    I make a script executable with chmod +x script.sh and run it as./script.sh, assuming the file has a valid shebang.
  4. What is the difference between running a script with./script.sh, bash script.sh, and source script.sh? [Basic]
    ./script.sh executes the file as a new process using its shebang.
  5. What does sourcing a script do differently from executing it? [Basic]
    Sourcing runs the file in the current shell instead of starting a separate shell process.
  6. How do you declare a variable in Bash, and why are spaces around = not allowed? [Basic]
    A Bash variable is assigned as name=value with no spaces around the equals sign.
  7. What is the difference between $var and ${var}? [Basic]
    $var and ${var} both expand a variable, but braces disambiguate the variable name and enable parameter expansion operations.
  8. What is the difference between single quotes and double quotes in Bash? [Basic]
    Single quotes preserve text literally, while double quotes still allow variable expansion, command substitution, and some escape sequences.
  9. Why should you quote variables, and what bug does unquoting cause? [Basic]
    Variables should usually be quoted to prevent word splitting and pathname expansion.
  10. What is command substitution, and what is the difference between $(...) and backticks? [Basic]
    Command substitution runs a command and replaces the expression with its stdout.
  11. How do you do arithmetic in Bash? [Basic]
    Bash arithmetic is normally done with $((expression)) for expansion or ((expression)) for evaluation and condition checks.
  12. What are the positional parameters $1, $2, and what are $@, $#, $0, $$, $?, $!? [Basic]
    $1, $2, and so on are positional arguments.
  13. What is the difference between $@ and $* when quoted? [Basic]
    When quoted, "$@" expands to separate quoted arguments, while "$*" expands to one string joined by the first character of IFS.
  14. What is $? used for, and how do you check the exit status of a command? [Basic]
    $?
  15. What does an exit code of 0 versus non-zero mean? [Basic]
    By convention, exit code 0 means success and a nonzero exit code means failure.
  16. What do set -e, set -u, set -o pipefail, and set -x do? [Basic]
    set -e exits on many unhandled command failures, set -u treats unset variables as errors, set -o pipefail makes a pipeline fail if any command in it fails, and set -x…
  17. Why is set -euo pipefail considered a safe default for scripts? [Basic]
    set -euo pipefail is considered a safer default because it stops many scripts from continuing with failed commands, unset variables, or hidden pipeline failures.
  18. Why does set -e not always behave as expected (e.g., inside pipelines or conditionals)? [Basic]
    set -e has exceptions: it does not always exit inside condition tests, parts of && or || chains, some subshells, or non-final commands in a pipeline unless pipefail…
  19. What is the difference between [ ], [[ ]], and (( )) in Bash? [Basic]
    [ ] is the traditional test command, [[ ]] is Bash's safer and more capable conditional expression, and (( )) is for arithmetic evaluation.
  20. Why do the brackets in [... ] require spaces? [Basic]
    The brackets in [...
  21. What are the common file test operators (-f, -d, -e, -r, -w, -x)? [Basic]
    Common file tests are -f for regular file, -d for directory, -e for exists, -r for readable, -w for writable, and -x for executable.
  22. What is the difference between -eq and = in test conditions? [Basic]
    -eq is for numeric equality in test expressions, while = compares strings.
  23. What are string test operators (-z, -n) used for? [Basic]
    -z checks whether a string is empty, and -n checks whether a string is non-empty.
  24. How do you write an if/elif/else statement in Bash? [Basic]
    An if statement evaluates a command or condition and branches with then, elif, else, and fi.
  25. How do you write a for loop over a list and a C-style for loop? [Basic]
    A list-style for loop iterates over words or array elements, while a C-style loop uses initialization, condition, and increment expressions.
  26. How do you write a while loop and an until loop? [Basic]
    A while loop runs while a condition succeeds; an until loop runs until a condition succeeds.
  27. What is the correct way to read a file line by line, and why not use for line in $(cat)? [Basic]
    The correct pattern is while IFS= read -r line; do...
  28. What does IFS do, and why set it when reading lines? [Basic]
    IFS is the Internal Field Separator.
  29. What does read -r do, and why is the -r flag important? [Basic]
    read -r tells read not to treat backslashes as escape characters.
  30. How do you write and call a function in Bash? [Basic]
    A Bash function is a reusable block defined as name() { commands; } or function name { commands; }.
  31. How do you pass arguments to a function and return a value or status? [Basic]
    Function arguments are accessed as $1, $2, and so on inside the function.
  32. What is the difference between a function returning a value via echo versus return? [Basic]
    echo outputs data to stdout, while return sets the function's exit status.
  33. What is local scope in a Bash function? [Basic]
    local creates a variable scoped to the current Bash function and its children.
  34. How do you parse command-line options with getopts? [Intermediate]
    getopts is Bash's built-in way to parse short command-line options.
  35. What is OPTARG, and how does getopts handle options with values? [Intermediate]
    OPTARG holds the value for the current option when getopts processes an option that requires an argument.
  36. What is a here-document, and when would you use one? [Intermediate]
    A here-document feeds a block of text to a command's stdin.
  37. What is a here-string (<<<), and how does it differ from a here-doc? [Intermediate]
    A here-string, written command <<< word, passes a single string to a command's stdin.
  38. What is the difference between >, >>, and 2> redirection? [Intermediate]
    > redirects stdout and overwrites the target file, >> redirects stdout and appends, and 2> redirects stderr.
  39. What does 2>&1 mean, and how do you redirect both stdout and stderr? [Intermediate]
    2>&1 means redirect stderr, file descriptor 2, to wherever stdout, file descriptor 1, currently points.
  40. What is /dev/null, and why redirect to it? [Intermediate]
    /dev/null is a special device that discards anything written to it and returns EOF when read.
  41. What is a pipe, and how does data flow through a | b | c? [Intermediate]
    A pipe connects the stdout of one command to the stdin of the next command.
  42. What is the difference between && and || in command chaining? [Intermediate]
    && runs the next command only if the previous command succeeds.
  43. What is the difference between a subshell and the current shell? [Intermediate]
    A subshell is a child shell process, often created with parentheses, pipelines, or command substitution.
  44. What is process substitution (<(...)), and when is it useful? [Intermediate]
    Process substitution, such as <(command), gives a command a file-like path connected to another command's output.
  45. What is the trap command, and how do you use it for cleanup on exit? [Intermediate]
    trap registers commands to run when the shell receives a signal or exits.
  46. How would you run cleanup code whether a script succeeds or fails? [Intermediate]
    I run cleanup on both success and failure by registering a cleanup function with trap...
  47. How do you create a secure temporary file or directory (mktemp)? [Intermediate]
    I use mktemp to create unpredictable temporary files or directories safely.
  48. How do you handle errors and provide a useful message on failure? [Intermediate]
    For useful error handling, I fail fast, print clear messages to stderr, include context, preserve exit codes where needed, and validate inputs before doing…
  49. What is the difference between exit and return? [Intermediate]
    exit terminates the current shell or script process, while return exits only the current function or sourced script.
  50. What are exit codes you should use, and what does a non-zero exit signal to a pipeline? [Intermediate]
    I use 0 for success and nonzero for failure.
  51. How do you debug a Bash script (set -x, bash -x, shellcheck)? [Intermediate]
    I debug Bash with bash -x script.sh, set -x around suspicious sections, meaningful logging, ShellCheck, and smaller reproducible inputs.
  52. What is shellcheck, and what kinds of issues does it catch? [Intermediate]
    ShellCheck is a static analysis tool for shell scripts.
  53. How do you check whether a command exists before using it? [Intermediate]
    I check whether a command exists with command -v name >/dev/null 2>&1.
  54. How do you loop over files safely when names contain spaces? [Intermediate]
    To loop over files safely, I use globs with quoted variables or find -print0 with read -d ''.
  55. What is the difference between glob expansion and regex in the shell? [Intermediate]
    Glob expansion is shell pathname matching, such as *.log matching files.
  56. What is parameter expansion, and what does ${var:-default} do? [Intermediate]
    Parameter expansion transforms or substitutes variable values.
  57. What does ${var:?message} do, and when would you use it? [Intermediate]
    ${var:?message} fails immediately with the message if var is unset or empty.
  58. What is the difference between ${var%pattern} and ${var#pattern}? [Intermediate]
    ${var%pattern} removes the shortest matching suffix, while ${var#pattern} removes the shortest matching prefix.
  59. How do you get the length of a string or the number of elements in an array? [Intermediate]
    ${#var} returns the length of a string, and ${#array[@]} returns the number of elements in an array.
  60. How do you declare and iterate over an array in Bash? [Intermediate]
    A Bash indexed array is declared with parentheses, such as arr=(a b c).
  61. What is an associative array, and how do you use one? [Intermediate]
    An associative array is a Bash map from string keys to values.
  62. How do you split a string on a delimiter in Bash? [Intermediate]
    For simple delimiters, I split a string by setting IFS and using read -r -a for arrays or read -r field1 field2 for named fields.
  63. How do you replace text in a variable using parameter expansion? [Intermediate]
    Bash can replace text in a variable using ${var/pattern/replacement} for the first match and ${var//pattern/replacement} for all matches.
  64. What is the difference between cut, awk, and sed for text processing? [Intermediate]
    cut is best for simple fixed delimiters or character/byte ranges, awk is a field-processing language for records, calculations, and conditions, and sed is a stream…
  65. How do you extract a specific column from delimited text with cut and with awk? [Intermediate]
    With cut, use -d to choose the delimiter and -f to choose fields.
  66. How does awk split lines into fields, and what are $1 and NF? [Intermediate]
    awk reads input as records, normally lines, and splits each record into fields.
  67. What is the difference between NR and NF in awk? [Advanced]
    NR is the current input record number, usually the line number across all files.
  68. How do you use awk to sum or average a column? [Advanced]
    To sum or average a column in awk, accumulate the numeric field in a variable and print the result in the END block.
  69. How do you use sed to find and replace text in a file (with a backup)? [Advanced]
    I use sed 's/old/new/g' for substitution and sed -i.bak for in-place editing with a backup.
  70. What is the difference between sed -i and sed without -i? [Advanced]
    sed without -i streams the modified result to stdout and leaves the source file unchanged.
  71. How do you print specific lines of a file with sed or awk? [Advanced]
    With sed, use -n and p to print specific lines or ranges.
  72. How do you count lines, words, and characters with wc? [Advanced]
    wc counts lines, words, bytes, and characters.
  73. How would you find the top N most frequent values in a log (sort | uniq -c | sort -rn)? [Advanced]
    To find the top N most frequent values, extract the field, sort it, count adjacent duplicates with uniq -c, sort numerically descending, and take the first N with head.
  74. Why must input be sorted before uniq, and what does uniq -c do? [Advanced]
    uniq compares only neighboring lines, so input must be sorted if I want global duplicate counts.
  75. How would you write a script to monitor disk usage and alert past a threshold? [Advanced]
    I would collect filesystem usage with df, compare the used percentage to a threshold, and alert through email, Slack, PagerDuty, or a monitoring push endpoint.
  76. How would you write a script to check if a process is running and restart it? [Advanced]
    I would check process state using systemd when available, because it is the service manager and can restart reliably.
  77. How would you write a backup script that rotates and keeps only the newest N files? [Advanced]
    A backup rotation script should create a timestamped backup, verify it exists and is non-empty, then delete older backups while keeping the newest N.
  78. How would you write a script to retry a flaky command with a delay? [Advanced]
    I write retries as a loop with a maximum attempt count, delay, and clear logging.
  79. How would you write a health-check script that polls a URL until it returns 200? [Advanced]
    I would poll the URL with curl, require HTTP 200, sleep between attempts, and enforce a timeout or maximum attempts.
  80. How do you schedule a script with cron, and what do the five cron fields mean? [Advanced]
    I schedule a script with cron by adding an entry to a user's crontab or /etc/cron.d.
  81. What is the difference between a cron job and a systemd timer? [Advanced]
    Cron is the traditional time-based scheduler.
  82. How would you make a long-running script run safely in the background? [Advanced]
    For a long-running script, I prefer running it under systemd, supervisord, Kubernetes, or another process manager.
  83. What is idempotency, and how do you make a script safe to run repeatedly? [Advanced]
    Idempotency means a script can be run repeatedly and converge to the same desired state without causing duplicate or destructive side effects.
  84. How do you securely handle secrets in a shell script (avoid hardcoding, use env or a vault)? [Advanced]
    I avoid hardcoding secrets in shell scripts.
  85. Why should you avoid putting secrets on the command line, and what leaks them? [Advanced]
    Secrets on the command line can leak through process listings, shell history, CI logs, audit logs, error messages, and monitoring agents.
  86. What is Groovy, and where do you most use it in a DevOps context? [Advanced]
    Groovy is a dynamic language for the JVM with Java interoperability and concise scripting features.
  87. How is Groovy used to write Jenkins pipelines? [Advanced]
    Groovy is used in Jenkins to define pipelines as code.
  88. What is the difference between a declarative and a scripted Jenkins pipeline in Groovy? [Advanced]
    Declarative Pipeline is a structured, opinionated Jenkins syntax inside a pipeline { } block.
  89. What is a Jenkins shared library, and how is it written in Groovy? [Advanced]
    A Jenkins shared library is reusable Pipeline code stored in a separate repository or configured library.
  90. How do you define and call a function (or step) in a Jenkins Groovy pipeline? [Advanced]
    In a Jenkinsfile, I can define a Groovy function with def name(args) {...
  91. How do you run shell commands from a Groovy pipeline (sh step) and capture output? [Advanced]
    In Jenkins Pipeline, I run shell commands with the sh step.
  92. How do you handle errors and retries in a Groovy pipeline (try/catch, retry, timeout)? [Advanced]
    In a Groovy pipeline, I handle errors with try/catch/finally, retry for transient failures, timeout for hung steps, and post blocks for cleanup or notifications.
  93. How do you use environment variables and credentials in a Groovy pipeline? [Advanced]
    I use the environment block for non-secret environment variables and withCredentials for secrets.
  94. How do you run stages in parallel in a Jenkins Groovy pipeline? [Advanced]
    In Declarative Pipeline, I use a parallel block inside a stage to run independent stages at the same time.
  95. What is the difference between Groovy and Java for scripting purposes? [Advanced]
    Groovy runs on the JVM and interoperates with Java, but it is more concise and dynamic for scripting.
  96. When would you choose Bash versus Groovy versus Python for an automation task? [Advanced]
    I choose Bash for simple OS orchestration and command glue, Groovy for Jenkins pipeline logic and JVM-integrated automation, and Python for larger automation that…
  97. What recent automation script have you written that saved significant manual effort? [Advanced]
    A strong example is a Bash/Groovy automation that replaced manual deployment validation.
  98. How do you make a script portable across different shells and systems? [Advanced]
    To make a script portable, I declare the intended shell, avoid non-portable features when targeting sh, check required commands, use POSIX-compatible options where…
  99. How would you structure a large script into reusable functions and a main entry point? [Advanced]
    I structure a large script with a small main function, focused helper functions, clear global constants, argument parsing, validation, logging, cleanup traps, and a…
  100. How do you write a dry-run mode into an automation script, and why is it valuable? [Advanced]
    Dry-run mode shows what the script would change without actually changing it.

← All interview topics