Friday, August 23, 2024

Nitheen Kumar

Shell Scripting Interview Questions and answers

Here’s a comprehensive list of over 100 shell scripting interview questions and answers. These cover a range of topics from basic concepts to advanced techniques.

Basic Concepts

  1. What is Shell Scripting?

    • Shell scripting is writing a series of commands for the shell to execute. It's used for automating repetitive tasks, managing system operations, and simplifying complex processes.
  2. What are the different types of shells available in UNIX/Linux?

    • Common shells include:
      • Bourne Shell (sh)
      • Bash (Bourne Again Shell, bash)
      • C Shell (csh)
      • Korn Shell (ksh)
      • Z Shell (zsh)
  3. How do you make a shell script executable?

    • Use the chmod command: chmod +x script.sh
  4. What does the #!/bin/bash line do?

    • This is called a shebang or hashbang. It indicates the path to the interpreter that should be used to execute the script.
  5. How do you execute a shell script?

    • You can execute it by running ./script.sh if it's executable, or by passing it as an argument to the interpreter, e.g., bash script.sh.

Variables

  1. How do you declare a variable in a shell script?

    • variable_name=value (No spaces around =)
  2. How do you access the value of a variable?

    • Use $variable_name or ${variable_name}
  3. What is the difference between $ and ${} when referencing variables?

    • ${} is used for more complex expressions or to disambiguate variable names.
  4. How do you declare a constant in a shell script?

    • Shell scripts don’t have built-in constants, but you can use readonly to prevent modification: readonly VAR=value
  5. What are positional parameters?

    • They are variables that hold the arguments passed to the script: $1, $2, etc.

Control Structures

  1. How do you write an if statement in shell scripting?

    if [ condition ]; then
    # commands elif [ other_condition ]; then # other commands else # default commands fi
  2. What is the purpose of the test command?

    • test is used to evaluate expressions, commonly for checking file attributes or string conditions.
  3. How do you write a for loop in shell scripting?

    for variable in list; do
    # commands done
  4. How do you write a while loop in shell scripting?

    while [ condition ]; do
    # commands done
  5. What is a case statement?

    • A case statement allows you to execute different blocks of code based on the value of a variable.
    case "$variable" in
    pattern1) # commands ;; pattern2) # commands ;; *) # default commands ;; esac

Functions

  1. How do you define a function in a shell script?

    function_name() {
    # commands }
  2. How do you call a function in a shell script?

    • Just use the function name followed by parentheses: function_name
  3. What is the purpose of return in functions?

    • return is used to exit a function and optionally pass back a status code.

File Handling

  1. How do you read a file line by line in a shell script?

    while IFS= read -r line; do
    # commands done < file.txt
  2. How do you append text to a file?

    • Use >> operator: echo "text" >> file.txt
  3. How do you check if a file exists?

    if [ -e filename ]; then
    # file exists fi
  4. What is the difference between -e and -f in file tests?

    • -e checks if a file exists, -f checks if it exists and is a regular file.

Strings and Arrays

  1. How do you concatenate strings in shell scripting?

    • Simply use variables next to each other: result="$string1$string2"
  2. How do you get the length of a string?

    • Use ${#variable}: length=${#string}
  3. How do you declare an array in shell scripting?

    array_name=(value1 value2 value3)
  4. How do you access array elements?

    • Use ${array_name[index]}: echo ${array_name[0]}
  5. How do you get the length of an array?

    • Use ${#array_name[@]}: length=${#array_name[@]}

Input and Output

  1. How do you read user input in a shell script?

    read -p "Enter something: " variable
  2. How do you redirect output to a file?

    • Use > for overwriting and >> for appending: command > file.txt or command >> file.txt
  3. What is the purpose of 2>&1?

    • It redirects standard error (file descriptor 2) to standard output (file descriptor 1), so both outputs go to the same place.

Error Handling

  1. How do you handle errors in shell scripts?

    • Check the exit status of commands using $?: if [ $? -ne 0 ]; then # handle error; fi
  2. What is trap used for?

    • trap allows you to specify commands to execute when the script receives a signal or exits.
  3. How do you exit a script with a specific exit code?

    • Use exit code: exit 1

Special Variables

  1. What does $? represent?

    • The exit status of the last executed command.
  2. What is $0, $1, $2, etc.?

    • $0 is the script name, $1, $2, etc., are positional parameters.
  3. What does $# represent?

      Shell Scripting Interview Questions and answers
    • The number of positional parameters.
  4. What does $@ represent?

    • All the positional parameters as separate words.
  5. What does $* represent?

    • All the positional parameters as a single word.

Advanced Topics

  1. What is a subshell?

    • A subshell is a child process created by the current shell. Commands executed in a subshell do not affect the parent shell.
  2. How do you use command substitution?

    • Use backticks `command` or $(command) to use the output of a command as an argument.
  3. What is process substitution?

    • Process substitution allows you to pass the output of a command as a file argument: <(command).
  4. How do you handle multiple commands in a single line?

    • Use ; or && for sequential execution, || for conditional execution: command1; command2 or command1 && command2
  5. What is the exec command used for?

    • exec replaces the shell with the specified command, without creating a new process.
  6. How do you debug a shell script?

    • Use set -x to enable debugging and set +x to disable it. bash -x script.sh also works.
  7. What is the difference between source and .?

    • Both source and . are used to execute commands from a file in the current shell. They are interchangeable.
  8. How do you create a cron job?

    • Use crontab -e to edit the cron table and add a job with a schedule and command.
  9. What is a here document?

    • A here document allows you to provide multiline input to a command or script:
    cat <<EOF
    This is a multiline string EOF
  10. How do you handle whitespace in shell scripting?

    • Enclose variables in quotes: "$variable"
  11. How do you use find command in shell scripting?

    • find searches for files and directories: find /path -name "pattern"
  12. What is awk and how is it used?

    • awk is a powerful text processing tool used for pattern scanning and reporting. Example: awk '{print $1}' file.txt
  13. What is sed and how is it used?

    • sed is a stream editor for filtering and transforming text. Example: sed 's/old/new/' file.txt
  14. How do you handle file permissions in a script?

    • Use chmod to set permissions: chmod 755 file.sh

Advanced Topics

  1. What is a symbolic link and how do you create one?

    • A symbolic link (or symlink) is a file that points to another file or directory. Create one using ln -s target link_name:
      ln -s /path/to/target /path/to/symlink
  2. How do you perform arithmetic operations in shell scripting?

    • Use expr, $((expression)), or let for arithmetic operations. Example:
      result=$((5 + 3))
  3. What is a named pipe (FIFO) and how do you create one?

    • A named pipe (FIFO) allows communication between processes. Create one with mkfifo:
      mkfifo /path/to/fifo
  4. What is the purpose of getopts?

    • getopts is used for parsing command-line options and arguments in scripts.
  5. How do you use getopts for option parsing?

    while getopts ":a:b:" opt; do
    case ${opt} in a ) a_value=$OPTARG ;; b ) b_value=$OPTARG ;; \? ) echo "Invalid option: -$OPTARG" 1>&2 ;; : ) echo "Invalid option: -$OPTARG requires an argument" 1>&2 ;; esac done
  6. What are environment variables and how do you set them?

    • Environment variables are variables available to all processes in the environment. Set them using export:
      export VAR=value
  7. How do you unset an environment variable?

    • Use unset:
      unset VAR
  8. What is exec used for in shell scripting?

    • exec replaces the shell with a specified command, not creating a new process:
      exec command
  9. What is the purpose of tee command?

    • tee reads from standard input and writes to standard output and files:
      command | tee file.txt
  10. What is nohup and how is it used?

    • nohup runs a command immune to hangups, with output redirected to a file:
      nohup command &
  11. How do you schedule a script to run periodically?

    • Use cron jobs. Edit with crontab -e and add a schedule:
      * * * * * /path/to/script.sh
  12. What are local variables in shell functions?

    • local defines variables with scope limited to the function:
      function my_func {
      local var=value }
  13. How do you debug a shell script?

    • Use set -x to trace commands and set -e to exit on errors. Also, you can use bash -x script.sh for debugging.
  14. What are shell built-ins?

    • Built-ins are commands built into the shell, such as cd, echo, export, and history.
  15. How do you use find to search for files and directories?

    • Example: find /path -name "*.txt" searches for .txt files.
  16. How do you use grep to search for text within files?

    • Example: grep "pattern" file.txt searches for pattern in file.txt.
  17. What are glob patterns?

    • Globs are wildcards used for filename expansion, such as *, ?, and [].
  18. How do you handle JSON data in a shell script?

    • Use jq, a command-line JSON processor. Example: jq '.key' file.json.
  19. How do you manage permissions with chmod?

    • Use numeric (e.g., 755) or symbolic (e.g., u+x) modes to set permissions.
  20. What is the difference between && and ||?

    • && executes the second command if the first succeeds, while || executes the second command if the first fails.
  21. How do you use xargs to handle command-line arguments?

    • xargs converts input into arguments for a command. Example: echo "file1 file2" | xargs rm.
  22. How do you create and use bash arrays?

    arr=(one two three)
    echo ${arr[0]} # Outputs: one
  23. What are parameter expansions in shell scripting?

    • Parameter expansions manipulate variable values. Example: ${var:-default} provides a default value if var is unset.
  24. How do you use read with multiple variables?

    read var1 var2 <<< "value1 value2"
  25. What is bash arithmetic expansion?

    • It allows arithmetic calculations within scripts. Example: result=$((5 + 3)).
  26. How do you perform a substring extraction in bash?

    string="HelloWorld"
    substr=${string:5:5} # Outputs: World
  27. How do you create a log file in a script?

    • Redirect output to a log file: command >> logfile.log 2>&1.
  28. What is a debugging trap?

    • A trap can be set to execute commands when a specific signal or condition occurs, useful for debugging.
  29. What are positional parameters and how do you use them?

    • Positional parameters are arguments passed to scripts. Use $1, $2, etc., to refer to them.
  30. How do you use sed to replace text?

    sed 's/old/new/g' file.txt
  31. How do you use awk for simple text processing?

    awk '{print $1}' file.txt
  32. What is shopt in bash?

    • shopt enables or disables shell options. Example: shopt -s nocaseglob.
  33. How do you check for command existence before running it?

    • Use command -v or type: if command -v command_name >/dev/null 2>&1; then # command exists; fi.
  34. What is exec used for in file descriptors?

    • exec can redirect file descriptors. Example: exec 3>output.txt opens file descriptor 3 for writing.
  35. How do you use find to delete files?

    • Combine with -exec: find /path -name "*.tmp" -exec rm {} \;.
  36. How do you use ps and grep to find processes?

    • Combine them to search for processes: ps aux | grep process_name.
  37. What is diff used for?

    • diff compares files line by line and shows differences.
  38. How do you handle special characters in filenames?

    • Use quotes or escape characters: echo "file\$name" or echo file\$name.
  39. What is basename and how do you use it?

    • basename strips directory and suffix from filenames. Example: basename /path/to/file.txt .txt.
  40. How do you use dirname in shell scripting?

    • dirname strips the filename from a path, returning the directory. Example: dirname /path/to/file.txt.
  41. What is printf and how is it used?

    • printf formats and prints text. Example: printf "Name: %s\n" "John".
  42. How do you use eval in shell scripting?

    • eval executes arguments as a shell command: eval "command with $var".
  43. What is the select statement used for?

    • select creates a menu for user selection:
      select option in "Option1" "Option2"; do
      # process option done
  44. How do you use trap to handle script termination?

    • trap executes commands when the script receives signals: trap 'commands' EXIT.
  45. What are here documents and how do you use them?

    • Provide multiline input directly in scripts:
      cat <<EOF
      Multiline text EOF
  46. How do you check for empty variables?

    • Use conditional expressions: if [ -z "$var" ]; then # variable is empty; fi.
  47. What is the use of cut command?

    • cut extracts sections from lines of files: cut -d':' -f1 file.txt.
  48. How do you use paste to merge files?

     - paste merges lines of files side by side: paste file1.txt file2.txt.

  49. What is xargs used for?

     - xargs builds and executes command lines from input: find . -name "*.txt" | xargs rm.

  50. How do you use sh and bash interchangeably?

     - bash is an enhanced version of sh. Use bash for advanced features not available in sh.

  51. What is the source command?

    - source executes commands from a file in the current shell: source script.sh.

  52. How do you use cut to extract fields from a file?

    - Example: cut -d',' -f1 file.csv extracts the first field from a CSV file.

  53. What is basename and dirname commands?

    - basename strips the directory part of a filename, dirname strips the file part, leaving the directory path.

  54. What is the difference between & and nohup?

     - & runs a command in the background, while nohup makes the command immune to hangups, useful for background processes that need to persist.

  55. How do you use ps command to list processes?

     - ps aux lists all running processes with detailed information.

  56. How do you check the exit status of the last command?

    - Use $?, which holds the exit status of the last command executed.

  57. What are shell options and how do you manage them?

    - Shell options control the behavior of the shell. Manage them using shopt and set.

  58. How do you use sed for in-place editing of files?

    - Use -i option: sed -i 's/old/new/g' file.txt.

  59. What is the difference between > and >> redirection operators?

    - > overwrites the file, while >> appends to it.

  60. How do you handle complex command sequences?

    - Use pipelines, &&, ||, and grouping: (command1 && command2) || command3.

  61. How do you create a tarball file?

     - Use tar command: tar -cvf archive.tar directory/.

  62. How do you extract a tarball file?

     - Use tar command: tar -xvf archive.tar.

  63. What is the cut command used for?

    - cut extracts specific columns or fields from files. Example: cut -d':' -f1 file.txt.

  64. How do you use chmod to set file permissions?

     - Example: chmod 755 file.sh sets read, write, and execute permissions for the owner, and read and execute for others.

  65. What is the find command for?

     - find searches for files and directories based on conditions. Example: find /path -type f -name "*.txt".

  66. How do you use grep to filter text?

     - Example: grep "pattern" file.txt searches for pattern in file.txt.

  67. How do you use awk for text processing?

     - awk processes and analyzes text. Example: awk '{print $1}' file.txt prints the first field.

  68. What is the date command used for?

    - date displays or sets the system date and time. Example: date +"%Y-%m-%d" formats the date.

  69. How do you perform conditional execution in shell scripting?

    - Use && for commands to execute if the previous command succeeds, and || for commands to execute if the previous command fails.

  70. What is a here document?

    - A here document allows you to pass multiple lines of input to commands:

    cat <<EOF
    Line1 Line2 EOF
  71. What is sed and how is it used for text processing?

     - sed is a stream editor for filtering and transforming text. Example: sed 's/old/new/g' file.txt.

  72. How do you use find and xargs together?

     - find can locate files, and xargs can pass them to another command. Example: find /path -name "*.txt" | xargs wc -l counts lines in all .txt files.

  73. How do you use grep with regular expressions?

     - grep supports regular expressions for flexible text searching: grep '^pattern' file.txt.

  74. How do you use awk to perform calculations?

    - awk can perform arithmetic operations: awk '{sum += $1} END {print sum}' file.txt.

  75. What is the cut command used for?

    - cut extracts sections from lines of files. Example: cut -d',' -f1 file.csv extracts the first field from a CSV file.

  76. How do you use printf for formatted output?

    - printf provides precise formatting: printf "Name: %-10s Age: %d\n" "John" 30.

  77. How do you handle user input in shell scripts?

    - Use read to capture user input: read -p "Enter value: " variable.

  78. What is diff used for?

     - diff compares two files line by line and shows differences.

  79. How do you use xargs for processing large numbers of arguments?

    - xargs builds and executes command lines from input. Example: find /path -type f | xargs rm removes files found.

  80. How do you create and use a symbolic link?

     - Create with ln -s target link_name. Use the symlink as if it were the original file.

  81. What is the alias command used for?

    - alias creates shortcuts for commands. Example: alias ll='ls -la'.

  82. How do you use find to execute commands on files?

    - Example: find /path -name "*.log" -exec rm {} \; finds and deletes .log files.

  83. What are trap signals used for?

     - trap can handle signals and execute commands on script termination or other events.

  84. How do you use ps to monitor processes?

    - Example: ps aux lists all running processes with details.

  85. How do you use ps to find a process by name?

    - Example: ps aux | grep process_name.

  86. What is shopt and how is it used?

    - shopt sets and unsets shell options. Example: shopt -s nocaseglob enables case-insensitive globbing.

  87. How do you use grep to search for text within a file?

    - Example: grep "text" filename searches for text in filename.

  88. What are file descriptors and how do you use them?

    - File descriptors are integer handles for files and input/output. Example: exec 3>file.txt opens file descriptor 3 for writing.

This list covers a wide array of shell scripting topics and should provide a solid foundation for preparing for interviews or improving your shell scripting skills.


Subscribe to get more Posts :