fbpx

Top 100 Shell Scripting Interview Questions and Answers

Top 100 Shell Scripting Interview Questions and Answers
Contents show

1. What is a shebang line in shell scripting?

Answer: The shebang line (#!) is a special character sequence that informs the system which interpreter should be used to execute the script. For example, #!/bin/bash indicates that the script should be executed using the Bash shell.


2. How do you comment out multiple lines in a shell script?

Answer: To comment out multiple lines, you can enclose them within <<COMMENT and COMMENT as shown below:

: <<COMMENT
This is a comment block.
It can span multiple lines.
COMMENT

3. Explain the difference between $ and $$ in shell scripting.

Answer: $ is used to access the value of a variable, while $$ represents the process ID of the current shell. For example, echo $USER prints the username, and echo $$ prints the process ID.


4. How can you pass arguments to a shell script?

Answer: Arguments are passed to a shell script through the command line. They can be accessed using $1, $2, etc., where $1 represents the first argument, $2 the second, and so on.


5. What is the purpose of the if-else statement in shell scripting?

Answer: The if-else statement allows conditional execution of code. It executes a block of code if a specified condition is true, and another block if the condition is false.

if [ condition ]; then
    # Code to execute if condition is true
else
    # Code to execute if condition is false
fi

6. How do you check if a file exists in a shell script?

Answer: You can use the -e operator to check if a file exists:

if [ -e "filename" ]; then
    echo "File exists."
else
    echo "File does not exist."
fi

7. Explain the purpose of a for loop in shell scripting.

Answer: A for loop allows you to iterate over a list of items. It executes a set of commands for each item in the list.

for item in list; do
    # Commands to execute
done

8. How do you read input from the user in a shell script?

Answer: You can use the read command to prompt the user for input and store it in a variable.

echo "Enter your name:"
read name
echo "Hello, $name!"

9. What is the purpose of backticks (`) in shell scripting?

Answer: Backticks are used for command substitution. They allow you to execute a command and use its output as part of another command.

result=`command`

10. How do you find the length of a string in shell scripting?

Answer: You can use the ${#string} syntax to get the length of a string.

string="Hello"
length=${#string}
echo "Length of string is $length"

11. Explain the purpose of the case statement in shell scripting.

Answer: The case statement is used for multi-way branching. It matches a value against a set of patterns and executes code associated with the first matching pattern.

case $variable in
    pattern1)
        # Code to execute for pattern1
        ;;
    pattern2)
        # Code to execute for pattern2
        ;;
    *)
        # Default code
        ;;
esac

12. How do you check if a directory exists in a shell script?

Answer: You can use the -d operator to check if a directory exists.

if [ -d "dirname" ]; then
    echo "Directory exists."
else
    echo "Directory does not exist."
fi

13. What is the purpose of the while loop in shell scripting?

Answer: The while loop executes a block of code as long as a specified condition is true.

while [ condition ]; do
    # Code to execute
done

14. How do you perform arithmetic operations in shell scripting?

Answer: You can use the expr command or $(( )) syntax for arithmetic operations.

result=$(expr 2 + 3)

or

result=$((2 + 3))

15. Explain the purpose of the trap command in shell scripting.

Answer: The trap command is used to specify how the shell should handle signals. It allows you to define actions to be taken when a signal is received.

trap "echo 'Signal received'" SIGINT

16. How do you redirect standard output and standard error in shell scripting?

Answer: To redirect standard output, use >. To redirect standard error, use 2>.

command > output.txt
command 2> error.txt

17. What is the purpose of the awk command in shell scripting?

Answer: awk is a powerful text processing tool. It scans a file line by line and allows actions to be performed on specific patterns within lines.

awk '{print $1}' file.txt

18. How do you find and replace text in a file using sed in shell scripting?

Answer: You can use the sed command for find and replace operations.

sed 's/old-text/new-text/' input.txt > output.txt

19. Explain the purpose of the cut command in shell scripting.

Answer: The cut command is used for cutting out sections from each line of files. It’s often used for extracting specific columns from text files.

cut -d',' -f1 file.csv

20. How do you get the current date and time in a shell script?

Answer: You can use the date command to get the current date and time.

current_date=$(date +"%Y-%m-%d")
current_time=$(date +"%H:%M:%S")

21. How do you perform string concatenation in shell scripting?

Answer: You can concatenate strings using the $ symbol.

string1="Hello"
string2=" World"
result="$string1$string2"

22. Explain the purpose of the grep command in shell scripting.

Answer: grep is used for pattern searching within files. It prints lines that contain a match to a specified pattern.

grep "pattern" file.txt

23. How do you check if a variable is set in shell scripting?

Answer: You can use the -v operator to check if a variable is set.

if [ -z ${variable+x} ]; then
    echo "Variable is unset"
else
    echo "Variable is set"
fi

24. What is the purpose of the select statement in shell scripting?

Answer: select is used for creating menus in scripts. It displays a numbered menu, and the user can select an option.

select option in Option1 Option2 Option3; do
    case $option in
        "Option1") echo "Option 1 selected";;
        "Option2") echo "Option 2 selected";;
        "Option3") echo "Option 3 selected";;
        *) echo "Invalid option";;
    esac
done

25. How do you perform floating-point arithmetic in shell scripting?

Answer: Bash does not support floating-point arithmetic directly. You can use tools like bc for this purpose.

result=$(echo "scale=2; 3.14/2" | bc)

26. Explain the purpose of the getopts command in shell scripting.

Answer: getopts is used for processing command-line options and arguments. It simplifies the handling of command-line options.

while getopts ":abc" option; do
    case $option in
        a) echo "Option 'a' is set";;
        b) echo "Option 'b' is set";;
        c) echo "Option 'c' is set";;
        \?) echo "Invalid option: -$OPTARG";;
    esac
done

27. How do you run a shell script in the background?

Answer: You can use the & symbol to run a shell script in the background.

./script.sh &

28. Explain the purpose of the until loop in shell scripting.

Answer: The until loop is similar to the while loop, but it continues executing a block of code as long as a specified condition is false.

until [ condition ]; do
    # Code to execute
done

29. How do you sort lines in a file alphabetically using shell scripting?

Answer: You can use the sort command for this purpose.

sort file.txt

30. What is the purpose of the declare command in shell scripting?

Answer: The declare command is used for defining variables and functions with specific attributes.

declare -i num=10   # num is an integer
declare -a array    # array is indexed

31. How do you check if a command exists in shell scripting?

Answer: You can use the command -v or type command to check if a command exists.

if command -v command_name &> /dev/null; then
    echo "Command exists"
else
    echo "Command does not exist"
fi

32. Explain the purpose of the tee command in shell scripting.

Answer: The tee command reads from standard input and writes to standard output and files. It’s often used in pipelines.

command | tee file.txt

33. How do you perform arithmetic operations with floating-point numbers in shell scripting?

Answer: You can use tools like bc or awk for floating-point arithmetic.

Using bc:

result=$(echo "scale=2; 3.14/2" | bc)

Using awk:

result=$(awk "BEGIN {print 3.14/2}")

34. What is the purpose of the getent command in shell scripting?

Answer: getent is used to get entries from the system’s name service switch libraries, including passwd, group, hosts, and more.

getent passwd

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

Answer: You can use a while loop with the read command.

while IFS=

 read -r line; do
    echo "$line"
done < file.txt

36. How do you find the length of a string in shell scripting?

Answer: You can use the ${#string} syntax to find the length of a string.

string="Hello, World!"
length=${#string}

37. Explain the purpose of the case statement in shell scripting.

Answer: The case statement is used for pattern matching. It’s particularly useful for menu-driven scripts.

case $variable in
    pattern1) command1;;
    pattern2) command2;;
    *) default_command;;
esac

38. How do you perform arithmetic operations with large numbers in shell scripting?

Answer: You can use bc for arbitrary precision arithmetic.

result=$(echo "12345678901234567890 * 2" | bc)

39. What is the purpose of the shift command in shell scripting?

Answer: shift is used to shift command-line arguments. It’s often used in scripts that process multiple arguments.

# Shifts all arguments one position to the left
shift

40. How do you handle errors in a shell script?

Answer: You can use the set -e option to make the script exit immediately if any command returns a non-zero status.

#!/bin/bash
set -e

41. Explain the purpose of the trap command in shell scripting.

Answer: trap is used to specify commands to run when the shell receives a signal.

trap 'echo Interrupted; exit' INT

42. How do you remove leading and trailing whitespace from a variable in shell scripting?

Answer: You can use parameter expansion with # and % to remove leading and trailing whitespace.

trimmed=${variable#* }
trimmed=${trimmed%* }

43. What is the purpose of the eval command in shell scripting?

Answer: eval is used to evaluate shell commands from a string.

command="ls -l"
eval $command

44. How do you find the process ID of a running script in shell?

Answer: You can use $$ to get the process ID of the current shell.

echo "The process ID of this script is $$"

45. Explain the purpose of the basename command in shell scripting.

Answer: basename extracts the base name from a path.

path="/path/to/some/file.txt"
filename=$(basename $path)

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

Answer: You can use the read command.

echo "Enter your name:"
read name

47. What is the purpose of the expr command in shell scripting?

Answer: expr is used for evaluating expressions.

result=$(expr 2 + 3)

48. How do you create a function in shell scripting?

Answer: Functions are defined like this:

function_name() {
    # Commands
}

49. Explain the purpose of the dirname command in shell scripting.

Answer: dirname extracts the directory component of a path.

path="/path/to/some/file.txt"
directory=$(dirname $path)

50. How do you redirect both standard output and standard error to the same file in shell scripting?

Answer: You can use 2>&1 to redirect standard error to the same location as standard output.

command > output.txt 2>&1

51. How do you check if a file exists in a shell script?

Answer: You can use the -e operator with an if statement.

if [ -e "file.txt" ]; then
    echo "File exists."
else
    echo "File does not exist."
fi

52. Explain the purpose of the for loop in shell scripting.

Answer: The for loop is used for iterating over a list of items.

for item in item1 item2 item3; do
    echo $item
done

53. How do you check if a variable is empty in shell scripting?

Answer: You can use the -z operator with an if statement.

if [ -z "$variable" ]; then
    echo "Variable is empty."
else
    echo "Variable is not empty."
fi

54. What is the purpose of the until loop in shell scripting?

Answer: The until loop is used for executing a block of code until a condition becomes true.

counter=0
until [ $counter -ge 5 ]; do
    echo $counter
    ((counter++))
done

55. How do you capture the output of a command into a variable in shell scripting?

Answer: You can use command substitution with backticks or $().

output=$(ls)

56. Explain the purpose of the select statement in shell scripting.

Answer: The select statement is used for creating interactive menus.

select option in "Option 1" "Option 2" "Option 3"; do
    case $option in
        "Option 1") echo "You chose Option 1";;
        "Option 2") echo "You chose Option 2";;
        "Option 3") echo "You chose Option 3";;
        *) echo "Invalid option";;
    esac
done

57. How do you generate random numbers in shell scripting?

Answer: You can use $RANDOM to generate random integers.

random_number=$((RANDOM % 100))

58. What is the purpose of the declare command in shell scripting?

Answer: declare is used for declaring variables with specific properties.

declare -i integer_variable=10

59. How do you perform floating-point arithmetic in shell scripting?

Answer: You can use tools like bc or awk.

result=$(echo "scale=2; 5/2" | bc)

60. What is the purpose of the getopts command in shell scripting?

Answer: getopts is used for parsing command-line options.

while getopts ":a:b:" option; do
    case $option in
        a) arg1=$OPTARG;;
        b) arg2=$OPTARG;;
        :) echo "Option -$OPTARG requires an argument.";;
        *) echo "Invalid option: -$OPTARG";;
    esac
done

61. How can you find the length of a string in shell scripting?

Answer: You can use the ${#variable} syntax to get the length of a string.

string="Hello, World!"
length=${#string}
echo "Length of string is $length"

62. Explain the purpose of the case statement in shell scripting.

Answer: The case statement is used for conditional branching based on pattern matching.

case $variable in
    pattern1) command1;;
    pattern2) command2;;
    *) default_command;;
esac

63. How do you redirect both stdout and stderr to a file in shell scripting?

Answer: You can use 2>&1 to redirect stderr to stdout, and then redirect stdout to a file.

command &> output.txt

64. What is the purpose of the trap command in shell scripting?

Answer: trap is used for specifying actions to be taken when a signal is received.

trap "echo 'Signal received'" SIGINT SIGTERM

65. How do you run a command in the background in shell scripting?

Answer: You can append & to the end of a command.

command &

66. Explain the use of the shift command in shell scripting.

Answer: shift is used for shifting command-line arguments.

$1, $2, $3...
shift
$1, $2, $3...

67. How do you create a function in shell scripting?

Answer: Functions are defined using the function keyword or simply by their name.

function my_function {
    echo "This is a function."
}

my_function

68. What is the purpose of the source or . command in shell scripting?

Answer: source or . is used for executing a script within the current shell environment.

source script.sh

69. How do you remove trailing whitespace from a variable in shell scripting?

Answer: You can use parameter expansion to trim whitespace.

variable="   text with spaces    "
trimmed_variable=${variable%% }

70. Explain the difference between > and >> operators for file redirection.

Answer: > overwrites a file, while >> appends to a file.

echo "Content" > file.txt   # Overwrite
echo "More content" >> file.txt   # Append

71. How can you determine if a file exists in shell scripting?

Answer: You can use the -e option with test or [ ] to check if a file exists.

if [ -e file.txt ]; then
    echo "File exists"
fi

72. Explain the purpose of a shebang (#!) in a shell script.

Answer: The shebang is used to specify the interpreter for the script. For example, #!/bin/bash indicates that the script should be interpreted using the Bash shell.

#!/bin/bash

73. How do you perform arithmetic operations in shell scripting?

Answer: Use expr or double parentheses (( )) for arithmetic operations.

result=$(expr 5 + 3)

or

result=$((5 + 3))

74. What is process substitution in shell scripting?

Answer: Process substitution allows the output of a command to appear as a file. It’s represented as <(command).

diff <(command1) <(command2)

75. How can you read input from a user in shell scripting?

Answer: Use the read command to prompt for and read input.

echo "Enter your name: "
read name
echo "Hello, $name!"

76. Explain the purpose of the getopts command in shell scripting.

Answer: getopts is used for parsing command-line options and arguments.

while getopts ":a:b:c" option; do
    case $option in
        a) echo "Option a: $OPTARG";;
        b) echo "Option b: $OPTARG";;
        c) echo "Option c";;
        \?) echo "Invalid option: -$OPTARG";;
    esac
done

77. How do you check if a variable is set in shell scripting?

Answer: Use the -v option with test or [ ] to check if a variable is set.

if [ -v variable ]; then
    echo "Variable is set"
fi

78. Explain the use of process substitution in shell scripting.

Answer: Process substitution allows a process’s input or output to be referred to as a file.

command < <(another_command)

79. What is the purpose of the until loop in shell scripting?

Answer: The until loop repeatedly executes a block of code until a condition becomes true.

until [ condition ]; do
    # code
done

80. How do you find the PID of the current shell in shell scripting?

Answer: Use the $$ variable to get the PID of the current shell.

echo "PID of current shell: $$"

81. How do you redirect both standard output (stdout) and standard error (stderr) to different files in a single command?

Answer: You can use the 2> operator to redirect stderr to a file and 1> to redirect stdout to another file in a single command.

command > output.txt 2> error.txt

82. Explain the difference between && and || in command chaining.

Answer: && is used to execute the next command only if the previous one succeeds (returns 0), while || executes the next command only if the previous one fails (returns a non-zero value).

command1 && command2
command1 || command2

83. How can you run a shell script as a background process?

Answer: Add an ampersand (&) at the end of the command to run the script in the background.

./myscript.sh &

84. Explain the purpose of the trap command in shell scripting.

Answer: The trap command is used to intercept and handle signals in a script, such as cleaning up resources before exiting.

trap 'cleanup_function' EXIT

85. How do you use command substitution to capture the output of a command into a variable?

Answer: You can use $(command) to capture the output of a command into a variable.

result=$(date)

86. What is a here document in shell scripting, and how is it used?

Answer: A here document (<<) is used to pass multiple lines of input to a command or script.

cat << EOF
This is
a multi-line
input.
EOF

87. How can you run a script with elevated privileges (as root) using sudo?

Answer: Use sudo followed by the script’s command to run it with elevated privileges.

sudo ./myscript.sh

88. Explain the concept of command substitution and provide an example.

Answer: Command substitution allows the output of a command to be used as part of another command.

files=$(ls)

89. How do you use the find command to search for files and directories in a specific directory?

Answer: Use the find command with the directory path and optional criteria.

find /path/to/search -name "*.txt"

90. What is the purpose of the cut command in shell scripting, and how is it used?

Answer: The cut command is used to extract sections from lines of files.

echo "Hello, World" | cut -d' ' -f2

91. How can you compare two strings in a shell script?

Answer: You can use the [ ] or [[ ]] test operators for string comparison.

if [ "$string1" == "$string2" ]; then
    echo "Strings are equal"
fi

92. Explain the purpose of the awk command in shell scripting.

Answer: awk is a powerful text processing tool that allows you to perform pattern scanning and text extraction.

echo "Hello World" | awk '{print $1}'

93. How do you use sed to perform find and replace operations in a file?

Answer: Use the s/old/new/g command in sed for find and replace.

sed -i 's/old/new/g' myfile.txt

94. Explain what a shell function is and how to define one.

Answer: A shell function is a set of commands grouped together as a single command. They can be defined as:

my_function() {
    echo "Hello, World!"
}

95. How can you loop through a range of numbers in a shell script?

Answer: You can use a for loop with a range.

for i in {1..5}; do
    echo $i
done

96. What is process substitution in shell scripting?

Answer: Process substitution allows you to use the output of a command as a file.

diff <(command1) <(command2)

97. How can you check if a file exists in a shell script?

Answer: Use the -e test operator to check if a file exists.

if [ -e "myfile.txt" ]; then
    echo "File exists"
fi

98. Explain the purpose of the case statement in shell scripting.

Answer: The case statement allows you to perform different actions based on the value of a variable.

case "$variable" in
    pattern1) command1 ;;
    pattern2) command2 ;;
    *) default_command ;;
esac

99. How can you read user input in a shell script?

Answer: Use the read command to get user input.

read -p "Enter your name: " name
echo "Hello, $name"

100. What is process substitution in shell scripting?

Answer: Process substitution allows you to use the output of a command as a file.

diff <(command1) <(command2)