InterviewPitch
Bash interview questions

Bash Interview Questions with Answers

Most Asked Bash Interview Questions for DevOps and System Administration Roles

100+ QuestionsDetailed AnswersCode ExamplesUpdated for 2026

Introduction

Bash is the most widely used shell on Linux and Unix systems, combining powerful command‑line execution with scripting capabilities for automation. This page collects 100 essential Bash interview questions – from basic syntax and variable handling to file operations, process management, text processing, and advanced scripting techniques – crucial for DevOps, system administration, and cloud engineering roles.

Why Bash?

  • Ubiquitous in Linux/Unix environments
  • Automates repetitive tasks and system administration
  • Integrates seamlessly with system commands and utilities
  • Core skill for DevOps, SRE, and infrastructure engineering
  • Powerful text processing with grep, sed, awk
  • Essential for CI/CD pipelines and cloud provisioning

Most Asked Bash Interview Questions

Beginner
1. What is Bash?

Bash stands for Bourne Again Shell. It is a command-line shell and scripting language used mainly in Linux and Unix systems.

Bash allows users to:

  • Run commands
  • Automate tasks
  • Create shell scripts
  • Manage files and processes
bash
#!/bin/bash
echo "Hello World"
Beginner
2. What is a shell script?

A shell script is a file containing a sequence of Bash commands that are executed automatically.

Shell scripts help automate repetitive tasks.

bash
#!/bin/bash

name="AK"

echo $name
Beginner
3. How do you declare variables in Bash?

Variables in Bash are declared without data types. No spaces should be used around =.

bash
#!/bin/bash

num1=10
num2=20

sum=$((num1 + num2))

echo $sum
Beginner
4. How do you perform arithmetic operations in Bash?

Arithmetic operations in Bash are usually done using $(( )).

bash
#!/bin/bash

if [ 10 -gt 5 ]
then
  echo "10 is greater"
fi
Beginner
5. What is an if statement in Bash?

An if statement is used to execute commands conditionally.

bash
#!/bin/bash

for i in 1 2 3 4 5
do
  echo $i
done
Beginner
6. What is a for loop in Bash?

A for loop is used to repeat commands multiple times.

bash
#!/bin/bash

count=1

while [ $count -le 5 ]
do
  echo $count
  count=$((count + 1))
done
Beginner
7. What is a while loop in Bash?

A while loop repeatedly executes commands while a condition remains true.

bash
#!/bin/bash

function greet() {
  echo "Hello AK"
}

greet
Beginner
8. What are functions in Bash?

Functions are reusable blocks of code used to perform specific tasks.

bash
#!/bin/bash

echo $1
echo $2
Beginner
9. What are positional parameters in Bash?

Positional parameters are command-line arguments passed to a script.

  • $1 → first argument
  • $2 → second argument
  • $# → total arguments
bash
#!/bin/bash

read -p "Enter your name: " name

echo "Welcome $name"
Beginner
10. How do you take user input in Bash?

The read command is used to take input from the user.

bash
#!/bin/bash

touch file.txt

if [ -f file.txt ]
then
  echo "File exists"
fi
Intermediate
11. How do you check if a file exists in Bash?

Bash provides test operators to check files and directories. Use -f for regular files, -d for directories.

bash
#!/bin/bash

case $1 in
  start)
    echo "Starting"
    ;;
  stop)
    echo "Stopping"
    ;;
  *)
    echo "Invalid option"
    ;;
esac
Intermediate
12. What is a case statement in Bash?

A case statement is used for multiple condition checks. It is similar to a switch statement in other languages.

bash
#!/bin/bash

arr=("apple" "banana" "mango")

echo ${arr[0]}
echo ${arr[1]}
Intermediate
13. What are arrays in Bash?

Arrays store multiple values in a single variable. Bash supports both indexed and associative arrays.

bash
#!/bin/bash

today=$(date)

echo $today
Intermediate
14. What is command substitution?

Command substitution allows the output of a command to be stored in a variable. Use $() or backticks.

bash
#!/bin/bash

grep "hello" file.txt
Intermediate
15. What is grep in Linux?

grep is a command used to search text patterns inside files. It supports regular expressions.

bash
#!/bin/bash

ps aux | grep nginx
Intermediate
16. How do you check running processes in Linux?

The ps command shows running processes. Use ps aux for all processes, or top for real-time.

bash
#!/bin/bash

find . -name "*.txt"
Advanced
17. What is the find command?

The find command searches for files and directories. It can filter by name, type, size, etc.

bash
#!/bin/bash

chmod +x script.sh
Advanced
18. What is chmod?

chmod changes file permissions in Linux. It can be used with octal (e.g., 755) or symbolic (u+x) modes.

bash
#!/bin/bash

tar -czvf backup.tar.gz folder/
Advanced
19. What is the tar command?

tar is used to archive and compress files. Common flags: -cvf (create), -xvf (extract).

bash
#!/bin/bash

echo "Current User: $USER"
echo "Home Directory: $HOME"
Advanced
20. What are environment variables in Bash?

Environment variables store system-wide values used by the shell and applications. Use export to make them available to child processes.

bash
#!/bin/bash

echo "Exit Status: $?"
Advanced
21. What is exit status in Bash?

Every command in Bash returns an exit status. 0 means success, non-zero indicates an error.

bash
#!/bin/bash

echo "Hello" > output.txt
echo "World" >> output.txt
cat < output.txt
Beginner
22. How do you use redirection (>, >>, <) in Bash?

Redirection is used to control input and output:

  • > – overwrite file with stdout
  • >> – append stdout to file
  • < – read from file as stdin
bash
#!/bin/bash

ls -la | grep ".txt"
Beginner
23. What are pipes (|) in Bash?

Pipes connect the stdout of one command to the stdin of another, allowing chaining.

bash
#!/bin/bash

sed -i 's/old/new/g' file.txt
Intermediate
24. How do you use sed for text replacement?

sed (stream editor) can perform search and replace. The syntax is sed 's/old/new/g'.

bash
#!/bin/bash

awk '{print $1}' data.txt
Intermediate
25. How do you use awk for text processing?

awk is a powerful text-processing tool that works with fields and patterns. It can extract columns, sum values, etc.

bash
#!/bin/bash

cat << EOF
Line 1
Line 2
EOF
Intermediate
26. What is a here document?

A here document (heredoc) allows multi-line input to a command. It uses << DELIMITER.

bash
#!/bin/bash

ls /nonexistent
echo "Exit code: $?"
Beginner
27. How do you check the exit status of the last command?

The variable $? holds the exit status of the most recently executed command.

bash
#!/bin/bash

for arg in "$*"; do echo "$arg"; done
for arg in "$@"; do echo "$arg"; done
Intermediate
28. What is the difference between $* and $@?

Both expand to all positional parameters, but with different behavior when quoted:

  • $* – expands to a single string with first character of IFS
  • $@ – expands each parameter as a separate quoted string
bash
#!/bin/bash

if [ -f "$1" ]; then
  echo "File exists"
fi
Beginner
29. How do you use the test command ([ ... ])?

The test command checks file types, compares values, and evaluates conditions. The [ is an alias for test.

bash
#!/bin/bash

echo *.txt
Beginner
30. What are glob patterns in Bash?

Glob patterns are wildcard characters used for filename expansion:

  • * – any characters
  • ? – any single character
  • [abc] – one of a, b, c
bash
#!/bin/bash

bash -x script.sh
Intermediate
31. How do you debug a Bash script?

Use bash -x script.sh to enable debug mode, or add set -x inside the script. Also use set -e to exit on error.

bash
#!/bin/bash

name='Alice'
greeting="Hello, $name"
echo $greeting
Intermediate
32. What is the difference between single quotes and double quotes in Bash?

Single quotes preserve the literal value of everything inside. Double quotes allow variable interpolation and command substitution.

bash
#!/bin/bash

trap 'echo "Interrupted"' INT
sleep 10
Advanced
33. How do you use trap to handle signals?

The trap command catches signals and executes a command or function. For example, trap 'echo "Interrupted"' INT.

bash
#!/bin/bash

(cd /tmp && pwd)
pwd
Intermediate
34. What is a subshell?

A subshell is a child shell process spawned from the current shell. Commands inside parentheses ( ) run in a subshell.

bash
#!/bin/bash

export MY_VAR="Hello"
./child_script.sh
Intermediate
35. How do you export variables?

Use the export command to make variables available to child processes: export VAR=value.

bash
#!/bin/bash

local var="inside function"
echo $var
Intermediate
36. What is the difference between local and global variables?

Global variables are accessible everywhere. Local variables are only accessible inside a function (declared with local).

bash
#!/bin/bash

source ./config.sh
echo $CONFIG_VAR
Intermediate
37. How do you use the source command?

The source command (or .) executes a script in the current shell environment. It's used to load functions or variables.

bash
#!/bin/bash

echo "Hello World"
Beginner
38. What is the shebang (#!) line?

The shebang line at the top of a script specifies the interpreter to use. Example: #!/bin/bash.

bash
#!/bin/bash

while getopts "f:" opt; do
  case $opt in
    f) echo "File: $OPTARG" ;;
  esac
done
Advanced
39. How do you handle command-line options (getopts)?

Use the built-in getopts command to parse options and arguments. It supports flags with values.

bash
#!/bin/bash

arr=(one two three)
for i in "${arr[@]}"; do
  echo $i
done
Intermediate
40. How do you use arrays in loops?

Iterate over array elements using for item in "${array[@]}".

bash
#!/bin/bash

cmd="ls -la"
eval $cmd
Advanced
41. What is the eval command?

eval constructs and executes commands from strings. Use with caution as it can be a security risk.

bash
#!/bin/bash

ls /tmp 2> errors.log
Intermediate
42. How do you redirect stderr?

Use 2> to redirect stderr to a file, or 2>&1 to merge stderr with stdout.

bash
#!/bin/bash

exec echo "Replaced shell"
Advanced
43. How do you use exec?

exec replaces the current shell with a new command, or can be used to redirect file descriptors.

bash
#!/bin/bash

ulimit -n 1024
echo "Open files limit: $(ulimit -n)"
Advanced
44. What is the ulimit command?

ulimit sets or displays resource limits for the shell and its child processes (file size, open files, etc.).

bash
#!/bin/bash

df -h
du -sh /home
Intermediate
45. How do you check disk usage in Linux?

Use df -h for disk space usage or du -sh for directory sizes.

bash
#!/bin/bash

free -m
Intermediate
46. How do you check memory usage?

Use free -h for memory usage, or top / htop for real-time monitoring.

bash
#!/bin/bash

ln file1 hardlink
ln -s file1 softlink
Advanced
49. How do you use crontab for scheduling?

crontab -e edits the user's cron jobs. Format: minute hour day month weekday command.

bash
#!/bin/bash

nohup ./long_running.sh &
Advanced
50. What is the nohup command?

nohup runs a command immune to hangup signals, so it continues after the terminal closes. Output is saved to nohup.out.

bash
#!/bin/bash

pkill -f "nginx"
Intermediate
51. How do you kill a process by name?

Use pkill process_name or killall process_name to kill processes by name.

bash
#!/bin/bash

kill -9 1234
Intermediate
52. What is the difference between kill and kill -9?

kill sends SIGTERM (graceful termination), while kill -9 sends SIGKILL (forceful, immediate termination).

bash
#!/bin/bash

if command; then
  echo "Success"
else
  echo "Failure"
fi
Intermediate
53. How do you check the exit status of a command in a script?

Check the $? variable after the command, or use if command; then for conditional execution.

bash
#!/bin/bash

var="Hello"
echo ${#var}
Intermediate
54. What is the $ syntax for variables?

${var} is parameter expansion. It allows manipulation like default values, length, substring removal, etc.

bash
#!/bin/bash

str="Hello World"
echo ${str:0:5}
Beginner
55. How do you get the length of a string in Bash?

Use ${#string} to get the length of a string.

bash
#!/bin/bash

text="hello world"
echo ${text/hello/hi}
Intermediate
56. How do you extract a substring?

Use ${string:position:length} to extract a substring.

bash
#!/bin/bash

var=""
if [ -z "$var" ]; then
  echo "Empty"
fi
Intermediate
57. How do you search and replace in a string?

Use ${string/pattern/replacement} for single, or ${string//pattern/replacement} for global replacement.

bash
#!/bin/bash

select option in "Start" "Stop"; do
  echo "Selected: $option"
  break
done
bash
#!/bin/bash

select option in "Start" "Stop"; do
  echo "Selected: $option"
  break
done
Beginner
58. How do you check if a variable is empty?

Use -z test: if [ -z "$var" ]; then checks if the variable is empty.

bash
#!/bin/bash

set -- arg1 arg2 arg3
shift
echo $1
Advanced
59. How do you use the select statement?

select generates a menu from a list. It's often used in interactive scripts.

bash
#!/bin/bash

read -t 5 -p "Enter name: " name
echo "Name: $name"
Intermediate
60. What is the shift command?

shift moves positional parameters to the left (e.g., $2 becomes $1). Useful for processing arguments.

bash
#!/bin/bash

printf "Name: %s
" "Alice"
Intermediate
61. How do you use the read command with a timeout?

Use read -t seconds to set a timeout for input.

bash
#!/bin/bash

temp_file=$(mktemp)
echo "Temp file: $temp_file"
Intermediate
62. How do you use the printf command?

printf formats and prints data. It's more portable than echo.

bash
#!/bin/bash

mktemp -d temp_dir_XXXXXX
Advanced
63. How do you create temporary files in Bash?

Use mktemp to create a temporary file or directory. It ensures a unique name.

bash
#!/bin/bash

echo "Hello" | tee file.txt
cat file.txt
Advanced
64. What is the mktemp command?

mktemp creates temporary files or directories securely. Use -d for directories.

bash
#!/bin/bash

single='$var'
double="$var"
echo "Single: $single, Double: $double"
Intermediate
65. How do you use the tee command?

tee reads from stdin and writes to both stdout and files. Useful for logging while displaying output.

bash
#!/bin/bash

declare -A map
map["key"]="value"
echo ${map["key"]}
Intermediate
66. What is the difference between single and double quotes for quoting?

Single quotes preserve literal value of everything. Double quotes allow variable interpolation and command substitution.

bash
#!/bin/bash

coproc ls -la
read -u ${COPROC[0]} line
echo $line
Advanced
67. How do you use associative arrays in Bash?

Declare with declare -A, then assign array[key]=value. Access with ${array[key]}.

bash
#!/bin/bash

sleep 5 &
wait
echo "Done"
Advanced
68. What is the coprocess feature?

A coprocess is a background process with its stdin and stdout connected to the shell using coproc.

bash
#!/bin/bash

sleep 10 &
jobs
Advanced
69. How do you use the wait command?

wait pauses until a background process finishes. It can take a job ID as argument.

bash
#!/bin/bash

sleep 30 &
fg
Advanced
70. How do you use the jobs command?

jobs lists background jobs in the current shell session. Use fg or bg to control them.

bash
#!/bin/bash

sleep 60 &
disown
Intermediate
71. What is the difference between foreground and background processes?

Foreground processes block the shell until they finish. Background processes run concurrently, allowing the shell to accept new commands.

bash
#!/bin/bash

screen -S my_session
tmux new -s my_session
Advanced
72. How do you use the disown command?

disown removes a job from the shell's job table, so it doesn't receive SIGHUP when the shell exits.

bash
#!/bin/bash

echo "Discarded" > /dev/null
Advanced
73. How do you use screen or tmux?

screen and tmux are terminal multiplexers. They allow multiple sessions, detaching and reattaching.

bash
#!/bin/bash

echo "one two three" | xargs echo
Beginner
74. What is the /dev/null device?

/dev/null is a special file that discards all data written to it. It's used to suppress output.

bash
#!/bin/bash

find . -name "*.txt" -exec rm {} ;
Advanced
75. How do you use the xargs command?

xargs builds and executes commands from standard input. It's often used with find to process many files.

bash
#!/bin/bash

sed '5d' file.txt
Advanced
76. How do you use the find command with -exec?

find -exec command \; executes a command on each found file. Use + instead of ; for efficiency.

bash
#!/bin/bash

awk '{sum += $1} END {print sum}' data.txt
Intermediate
77. How do you use sed to delete lines?

Use sed 'Nd' to delete line N, or sed '/pattern/d' to delete matching lines.

bash
#!/bin/bash

if [[ "hello" == hello ]]; then
  echo "Match"
fi
Intermediate
78. How do you use awk to sum columns?

awk '{sum += $1} END {print sum}' sums the first column of input.

bash
#!/bin/bash

if [[ -z "$var" ]]; then
  echo "Empty"
fi
Intermediate
79. What is the difference between == and = in Bash?

In [[ ]], == and = are both used for pattern matching. In [ ], = is the only string comparison operator.

bash
#!/bin/bash

set -e
ls /nonexistent
echo "This won't run"
Intermediate
80. How do you use the [[ ... ]] test construct?

[[ ]] is an enhanced test construct with regex matching, pattern matching, and no word splitting.

bash
#!/bin/bash

readarray lines < file.txt
echo ${lines[0]}
Advanced
81. What are the shell options (set -e, -x, etc.)?

set -e exits on error, set -x prints commands, set -u treats unset variables as error. Use set +e to disable.

bash
#!/bin/bash

declare -i num=5
echo $num
Advanced
82. How do you use the readarray/mapfile commands?

readarray (or mapfile) reads lines from stdin into an array. Useful for reading files into arrays.

bash
#!/bin/bash

export VAR="exported"
set | grep VAR
Advanced
83. How do you use the declare command?

declare sets variable attributes. Options: -i integer, -a array, -A associative array, -r read-only.

bash
#!/bin/bash

trap 'echo "Error on line $LINENO"' ERR
false
Intermediate
84. What is the difference between export and set?

export makes variables available to child processes. set sets shell options or positional parameters.

bash
#!/bin/bash

# Daemon logic (simplified)
(
  umask 0
  cd /tmp
  exec > /dev/null 2>&1
  while true; do
    echo "Daemon running"
    sleep 10
  done
) &
Advanced
85. How do you use the trap command with ERR?

trap 'command' ERR executes a command whenever a command returns a non-zero exit status.

bash
#!/bin/bash

logger -t myscript "Started script"
Advanced
86. How do you write a script that daemonizes?

A daemon script typically forks a child, closes file descriptors, changes directory, and sets umask.

bash
#!/bin/bash

while IFS=',' read -r col1 col2; do
  echo "$col1 - $col2"
done < data.csv
Advanced
87. How do you use the logger command for system logging?

logger sends messages to the system log. Use -t to tag the message.

bash
#!/bin/bash

expect -c '
spawn ssh user@host
expect "password:"
send "mypassword
"
expect "$"
send "ls
"
expect "$"
send "exit
"
'
Advanced
88. How do you parse CSV files in Bash?

Use awk -F',' or while IFS=',' read -r col1 col2 to parse CSV.

bash
#!/bin/bash

flock -x /tmp/lockfile -c "echo 'Lock acquired'";
Advanced
89. How do you use the expect command for automation?

expect automates interactive applications by sending/receiving strings. Useful for SSH, FTP, etc.

bash
#!/bin/bash

tail -f /var/log/syslog | grep "error"
Advanced
90. How do you use the flock command for file locking?

flock acquires a lock on a file to prevent concurrent access. Used in scripts to ensure exclusive execution.

bash
#!/bin/bash

watch -n 1 "df -h"
Intermediate
91. How do you monitor log files in real-time (tail -f)?

tail -f file.log displays new lines as they are written. Combine with grep to filter.

bash
#!/bin/bash

# See code47 for link explanation (reuse)
# This is a placeholder
echo "See code47"
Intermediate
92. How do you use the watch command?

watch runs a command repeatedly, showing output every 2 seconds by default. Useful for monitoring.

bash
#!/bin/bash

stat -c %a file.txt
Intermediate
94. How do you check file permissions in octal?

Use stat -c %a file or stat --format='%a' file to get octal permissions.

bash
#!/bin/bash

lsof /var/log/syslog
Advanced
95. How do you use the umask command?

umask sets the default file creation permissions. It subtracts the mask from the base permissions (666 for files, 777 for directories).

bash
#!/bin/bash

netstat -tuln
Advanced
96. How do you use the lsof command?

lsof lists open files. Useful to check which process is using a file or port.

bash
#!/bin/bash

ss -tuln
Advanced
97. How do you use the netstat command?

netstat displays network connections, routing tables, and interface statistics. Use -tuln to show listening ports.

bash
#!/bin/bash

curl -s -o page.html https://example.com
Advanced
98. How do you use the ss command?

ss is a modern replacement for netstat. It shows socket statistics and is faster.

bash
#!/bin/bash

wget -q https://example.com/file.zip
Advanced
99. How do you use the curl command in scripts?

curl transfers data from or to a server. In scripts, use -s for silent, -o for output, and -H for headers.

bash
#!/bin/bash

echo "This is code99 for the command pattern (placeholder)"
Advanced
100. How do you use the wget command?

wget downloads files from the web. Use -q for quiet, -O for output file, and --header for custom headers.

bash
#!/bin/bash

echo "This is code100 for the prototype pattern (placeholder)"