Bash Interview Questions with Answers
Most Asked Bash Interview Questions for DevOps and System Administration Roles
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
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
#!/bin/bash
echo "Hello World"A shell script is a file containing a sequence of Bash commands that are executed automatically.
Shell scripts help automate repetitive tasks.
#!/bin/bash
name="AK"
echo $nameVariables in Bash are declared without data types. No spaces should be used around =.
#!/bin/bash
num1=10
num2=20
sum=$((num1 + num2))
echo $sumArithmetic operations in Bash are usually done using $(( )).
#!/bin/bash
if [ 10 -gt 5 ]
then
echo "10 is greater"
fiAn if statement is used to execute commands conditionally.
#!/bin/bash
for i in 1 2 3 4 5
do
echo $i
doneA for loop is used to repeat commands multiple times.
#!/bin/bash
count=1
while [ $count -le 5 ]
do
echo $count
count=$((count + 1))
doneA while loop repeatedly executes commands while a condition remains true.
#!/bin/bash
function greet() {
echo "Hello AK"
}
greetFunctions are reusable blocks of code used to perform specific tasks.
#!/bin/bash
echo $1
echo $2Positional parameters are command-line arguments passed to a script.
- $1 → first argument
- $2 → second argument
- $# → total arguments
#!/bin/bash
read -p "Enter your name: " name
echo "Welcome $name"The read command is used to take input from the user.
#!/bin/bash
touch file.txt
if [ -f file.txt ]
then
echo "File exists"
fiBash provides test operators to check files and directories. Use -f for regular files, -d for directories.
#!/bin/bash
case $1 in
start)
echo "Starting"
;;
stop)
echo "Stopping"
;;
*)
echo "Invalid option"
;;
esacA case statement is used for multiple condition checks. It is similar to a switch statement in other languages.
#!/bin/bash
arr=("apple" "banana" "mango")
echo ${arr[0]}
echo ${arr[1]}Arrays store multiple values in a single variable. Bash supports both indexed and associative arrays.
#!/bin/bash
today=$(date)
echo $todayCommand substitution allows the output of a command to be stored in a variable. Use $() or backticks.
#!/bin/bash
grep "hello" file.txtgrep is a command used to search text patterns inside files. It supports regular expressions.
#!/bin/bash
ps aux | grep nginxThe ps command shows running processes. Use ps aux for all processes, or top for real-time.
#!/bin/bash
find . -name "*.txt"The find command searches for files and directories. It can filter by name, type, size, etc.
#!/bin/bash
chmod +x script.shchmod changes file permissions in Linux. It can be used with octal (e.g., 755) or symbolic (u+x) modes.
#!/bin/bash
tar -czvf backup.tar.gz folder/tar is used to archive and compress files. Common flags: -cvf (create), -xvf (extract).
#!/bin/bash
echo "Current User: $USER"
echo "Home Directory: $HOME"Environment variables store system-wide values used by the shell and applications. Use export to make them available to child processes.
#!/bin/bash
echo "Exit Status: $?"Every command in Bash returns an exit status. 0 means success, non-zero indicates an error.
#!/bin/bash
echo "Hello" > output.txt
echo "World" >> output.txt
cat < output.txtRedirection is used to control input and output:
>– overwrite file with stdout>>– append stdout to file<– read from file as stdin
#!/bin/bash
ls -la | grep ".txt"Pipes connect the stdout of one command to the stdin of another, allowing chaining.
#!/bin/bash
sed -i 's/old/new/g' file.txtsed (stream editor) can perform search and replace. The syntax is sed 's/old/new/g'.
#!/bin/bash
awk '{print $1}' data.txtawk is a powerful text-processing tool that works with fields and patterns. It can extract columns, sum values, etc.
#!/bin/bash
cat << EOF
Line 1
Line 2
EOFA here document (heredoc) allows multi-line input to a command. It uses << DELIMITER.
#!/bin/bash
ls /nonexistent
echo "Exit code: $?"The variable $? holds the exit status of the most recently executed command.
#!/bin/bash
for arg in "$*"; do echo "$arg"; done
for arg in "$@"; do echo "$arg"; doneBoth 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
#!/bin/bash
if [ -f "$1" ]; then
echo "File exists"
fiThe test command checks file types, compares values, and evaluates conditions. The [ is an alias for test.
#!/bin/bash
echo *.txtGlob patterns are wildcard characters used for filename expansion:
*– any characters?– any single character[abc]– one of a, b, c
#!/bin/bash
bash -x script.shUse bash -x script.sh to enable debug mode, or add set -x inside the script. Also use set -e to exit on error.
#!/bin/bash
name='Alice'
greeting="Hello, $name"
echo $greetingSingle quotes preserve the literal value of everything inside. Double quotes allow variable interpolation and command substitution.
#!/bin/bash
trap 'echo "Interrupted"' INT
sleep 10The trap command catches signals and executes a command or function. For example, trap 'echo "Interrupted"' INT.
#!/bin/bash
(cd /tmp && pwd)
pwdA subshell is a child shell process spawned from the current shell. Commands inside parentheses ( ) run in a subshell.
#!/bin/bash
export MY_VAR="Hello"
./child_script.shUse the export command to make variables available to child processes: export VAR=value.
#!/bin/bash
local var="inside function"
echo $varGlobal variables are accessible everywhere. Local variables are only accessible inside a function (declared with local).
#!/bin/bash
source ./config.sh
echo $CONFIG_VARThe source command (or .) executes a script in the current shell environment. It's used to load functions or variables.
#!/bin/bash
echo "Hello World"The shebang line at the top of a script specifies the interpreter to use. Example: #!/bin/bash.
#!/bin/bash
while getopts "f:" opt; do
case $opt in
f) echo "File: $OPTARG" ;;
esac
doneUse the built-in getopts command to parse options and arguments. It supports flags with values.
#!/bin/bash
arr=(one two three)
for i in "${arr[@]}"; do
echo $i
doneIterate over array elements using for item in "${array[@]}".
#!/bin/bash
cmd="ls -la"
eval $cmdeval constructs and executes commands from strings. Use with caution as it can be a security risk.
#!/bin/bash
ls /tmp 2> errors.logUse 2> to redirect stderr to a file, or 2>&1 to merge stderr with stdout.
#!/bin/bash
exec echo "Replaced shell"exec replaces the current shell with a new command, or can be used to redirect file descriptors.
#!/bin/bash
ulimit -n 1024
echo "Open files limit: $(ulimit -n)"ulimit sets or displays resource limits for the shell and its child processes (file size, open files, etc.).
#!/bin/bash
df -h
du -sh /homeUse df -h for disk space usage or du -sh for directory sizes.
#!/bin/bash
free -mUse free -h for memory usage, or top / htop for real-time monitoring.
#!/bin/bash
ln file1 hardlink
ln -s file1 softlinkHard links point directly to the inode; soft links are symbolic pointers to a file path. Soft links can cross filesystems.
#!/bin/bash
ln -s /usr/bin/python python_linkUse ln -s target link_name to create a symbolic link.
#!/bin/bash
crontab -ecrontab -e edits the user's cron jobs. Format: minute hour day month weekday command.
#!/bin/bash
nohup ./long_running.sh &nohup runs a command immune to hangup signals, so it continues after the terminal closes. Output is saved to nohup.out.
#!/bin/bash
pkill -f "nginx"Use pkill process_name or killall process_name to kill processes by name.
#!/bin/bash
kill -9 1234kill sends SIGTERM (graceful termination), while kill -9 sends SIGKILL (forceful, immediate termination).
#!/bin/bash
if command; then
echo "Success"
else
echo "Failure"
fiCheck the $? variable after the command, or use if command; then for conditional execution.
#!/bin/bash
var="Hello"
echo ${#var}${var} is parameter expansion. It allows manipulation like default values, length, substring removal, etc.
#!/bin/bash
str="Hello World"
echo ${str:0:5}Use ${#string} to get the length of a string.
#!/bin/bash
text="hello world"
echo ${text/hello/hi}Use ${string:position:length} to extract a substring.
#!/bin/bash
var=""
if [ -z "$var" ]; then
echo "Empty"
fiUse ${string/pattern/replacement} for single, or ${string//pattern/replacement} for global replacement.
#!/bin/bash
select option in "Start" "Stop"; do
echo "Selected: $option"
break
done#!/bin/bash
select option in "Start" "Stop"; do
echo "Selected: $option"
break
doneUse -z test: if [ -z "$var" ]; then checks if the variable is empty.
#!/bin/bash
set -- arg1 arg2 arg3
shift
echo $1select generates a menu from a list. It's often used in interactive scripts.
#!/bin/bash
read -t 5 -p "Enter name: " name
echo "Name: $name"shift moves positional parameters to the left (e.g., $2 becomes $1). Useful for processing arguments.
#!/bin/bash
printf "Name: %s
" "Alice"Use read -t seconds to set a timeout for input.
#!/bin/bash
temp_file=$(mktemp)
echo "Temp file: $temp_file"printf formats and prints data. It's more portable than echo.
#!/bin/bash
mktemp -d temp_dir_XXXXXXUse mktemp to create a temporary file or directory. It ensures a unique name.
#!/bin/bash
echo "Hello" | tee file.txt
cat file.txtmktemp creates temporary files or directories securely. Use -d for directories.
#!/bin/bash
single='$var'
double="$var"
echo "Single: $single, Double: $double"tee reads from stdin and writes to both stdout and files. Useful for logging while displaying output.
#!/bin/bash
declare -A map
map["key"]="value"
echo ${map["key"]}Single quotes preserve literal value of everything. Double quotes allow variable interpolation and command substitution.
#!/bin/bash
coproc ls -la
read -u ${COPROC[0]} line
echo $lineDeclare with declare -A, then assign array[key]=value. Access with ${array[key]}.
#!/bin/bash
sleep 5 &
wait
echo "Done"A coprocess is a background process with its stdin and stdout connected to the shell using coproc.
#!/bin/bash
sleep 10 &
jobswait pauses until a background process finishes. It can take a job ID as argument.
#!/bin/bash
sleep 30 &
fgjobs lists background jobs in the current shell session. Use fg or bg to control them.
#!/bin/bash
sleep 60 &
disownForeground processes block the shell until they finish. Background processes run concurrently, allowing the shell to accept new commands.
#!/bin/bash
screen -S my_session
tmux new -s my_sessiondisown removes a job from the shell's job table, so it doesn't receive SIGHUP when the shell exits.
#!/bin/bash
echo "Discarded" > /dev/nullscreen and tmux are terminal multiplexers. They allow multiple sessions, detaching and reattaching.
#!/bin/bash
echo "one two three" | xargs echo/dev/null is a special file that discards all data written to it. It's used to suppress output.
#!/bin/bash
find . -name "*.txt" -exec rm {} ;xargs builds and executes commands from standard input. It's often used with find to process many files.
#!/bin/bash
sed '5d' file.txtfind -exec command \; executes a command on each found file. Use + instead of ; for efficiency.
#!/bin/bash
awk '{sum += $1} END {print sum}' data.txtUse sed 'Nd' to delete line N, or sed '/pattern/d' to delete matching lines.
#!/bin/bash
if [[ "hello" == hello ]]; then
echo "Match"
fiawk '{sum += $1} END {print sum}' sums the first column of input.
#!/bin/bash
if [[ -z "$var" ]]; then
echo "Empty"
fiIn [[ ]], == and = are both used for pattern matching. In [ ], = is the only string comparison operator.
#!/bin/bash
set -e
ls /nonexistent
echo "This won't run"[[ ]] is an enhanced test construct with regex matching, pattern matching, and no word splitting.
#!/bin/bash
readarray lines < file.txt
echo ${lines[0]}set -e exits on error, set -x prints commands, set -u treats unset variables as error. Use set +e to disable.
#!/bin/bash
declare -i num=5
echo $numreadarray (or mapfile) reads lines from stdin into an array. Useful for reading files into arrays.
#!/bin/bash
export VAR="exported"
set | grep VARdeclare sets variable attributes. Options: -i integer, -a array, -A associative array, -r read-only.
#!/bin/bash
trap 'echo "Error on line $LINENO"' ERR
falseexport makes variables available to child processes. set sets shell options or positional parameters.
#!/bin/bash
# Daemon logic (simplified)
(
umask 0
cd /tmp
exec > /dev/null 2>&1
while true; do
echo "Daemon running"
sleep 10
done
) &trap 'command' ERR executes a command whenever a command returns a non-zero exit status.
#!/bin/bash
logger -t myscript "Started script"A daemon script typically forks a child, closes file descriptors, changes directory, and sets umask.
#!/bin/bash
while IFS=',' read -r col1 col2; do
echo "$col1 - $col2"
done < data.csvlogger sends messages to the system log. Use -t to tag the message.
#!/bin/bash
expect -c '
spawn ssh user@host
expect "password:"
send "mypassword
"
expect "$"
send "ls
"
expect "$"
send "exit
"
'Use awk -F',' or while IFS=',' read -r col1 col2 to parse CSV.
#!/bin/bash
flock -x /tmp/lockfile -c "echo 'Lock acquired'";expect automates interactive applications by sending/receiving strings. Useful for SSH, FTP, etc.
#!/bin/bash
tail -f /var/log/syslog | grep "error"flock acquires a lock on a file to prevent concurrent access. Used in scripts to ensure exclusive execution.
#!/bin/bash
watch -n 1 "df -h"tail -f file.log displays new lines as they are written. Combine with grep to filter.
#!/bin/bash
# See code47 for link explanation (reuse)
# This is a placeholder
echo "See code47"watch runs a command repeatedly, showing output every 2 seconds by default. Useful for monitoring.
#!/bin/bash
stat -c %a file.txtHard links are direct references to the inode; soft links are symbolic pointers. Hard links cannot span filesystems.
#!/bin/bash
umask 022
touch newfile
ls -l newfileUse stat -c %a file or stat --format='%a' file to get octal permissions.
#!/bin/bash
lsof /var/log/syslogumask sets the default file creation permissions. It subtracts the mask from the base permissions (666 for files, 777 for directories).
#!/bin/bash
netstat -tulnlsof lists open files. Useful to check which process is using a file or port.
#!/bin/bash
ss -tulnnetstat displays network connections, routing tables, and interface statistics. Use -tuln to show listening ports.
#!/bin/bash
curl -s -o page.html https://example.comss is a modern replacement for netstat. It shows socket statistics and is faster.
#!/bin/bash
wget -q https://example.com/file.zipcurl transfers data from or to a server. In scripts, use -s for silent, -o for output, and -H for headers.
#!/bin/bash
echo "This is code99 for the command pattern (placeholder)"wget downloads files from the web. Use -q for quiet, -O for output file, and --header for custom headers.
#!/bin/bash
echo "This is code100 for the prototype pattern (placeholder)"