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
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.
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
)
- Bourne Shell (
- Common shells include:
How do you make a shell script executable?
- Use the
chmod
command:chmod +x script.sh
- Use the
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.
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
.
- You can execute it by running
Variables
How do you declare a variable in a shell script?
variable_name=value
(No spaces around=
)
How do you access the value of a variable?
- Use
$variable_name
or${variable_name}
- Use
What is the difference between
$
and${}
when referencing variables?${}
is used for more complex expressions or to disambiguate variable names.
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
- Shell scripts don’t have built-in constants, but you can use
What are positional parameters?
- They are variables that hold the arguments passed to the script:
$1
,$2
, etc.
- They are variables that hold the arguments passed to the script:
Control Structures
How do you write an
if
statement in shell scripting?if [ condition ]; then# commands elif [ other_condition ]; then # other commands else # default commands fi
What is the purpose of the
test
command?test
is used to evaluate expressions, commonly for checking file attributes or string conditions.
How do you write a
for
loop in shell scripting?for variable in list; do# commands done
How do you write a
while
loop in shell scripting?while [ condition ]; do# commands done
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" inpattern1) # commands ;; pattern2) # commands ;; *) # default commands ;; esac
- A
Functions
How do you define a function in a shell script?
function_name() {# commands }
How do you call a function in a shell script?
- Just use the function name followed by parentheses:
function_name
- Just use the function name followed by parentheses:
What is the purpose of
return
in functions?return
is used to exit a function and optionally pass back a status code.
File Handling
How do you read a file line by line in a shell script?
while IFS= read -r line; do# commands done < file.txt
How do you append text to a file?
- Use
>>
operator:echo "text" >> file.txt
- Use
How do you check if a file exists?
if [ -e filename ]; then# file exists fi
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
How do you concatenate strings in shell scripting?
- Simply use variables next to each other:
result="$string1$string2"
- Simply use variables next to each other:
How do you get the length of a string?
- Use
${#variable}
:length=${#string}
- Use
How do you declare an array in shell scripting?
array_name=(value1 value2 value3)How do you access array elements?
- Use
${array_name[index]}
:echo ${array_name[0]}
- Use
How do you get the length of an array?
- Use
${#array_name[@]}
:length=${#array_name[@]}
- Use
Input and Output
How do you read user input in a shell script?
read -p "Enter something: " variableHow do you redirect output to a file?
- Use
>
for overwriting and>>
for appending:command > file.txt
orcommand >> file.txt
- Use
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
How do you handle errors in shell scripts?
- Check the exit status of commands using
$?
:if [ $? -ne 0 ]; then # handle error; fi
- Check the exit status of commands using
What is
trap
used for?trap
allows you to specify commands to execute when the script receives a signal or exits.
How do you exit a script with a specific exit code?
- Use
exit code
:exit 1
- Use
Special Variables
What does
$?
represent?- The exit status of the last executed command.
What is
$0
,$1
,$2
, etc.?$0
is the script name,$1
,$2
, etc., are positional parameters.
What does
$#
represent?What does
$@
represent?- All the positional parameters as separate words.
What does
$*
represent?- All the positional parameters as a single word.
Advanced Topics
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.
How do you use command substitution?
- Use backticks
`command`
or$(command)
to use the output of a command as an argument.
- Use backticks
What is process substitution?
- Process substitution allows you to pass the output of a command as a file argument:
<(command)
.
- Process substitution allows you to pass the output of a command as a file argument:
How do you handle multiple commands in a single line?
- Use
;
or&&
for sequential execution,||
for conditional execution:command1; command2
orcommand1 && command2
- Use
What is the
exec
command used for?exec
replaces the shell with the specified command, without creating a new process.
How do you debug a shell script?
- Use
set -x
to enable debugging andset +x
to disable it.bash -x script.sh
also works.
- Use
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.
- Both
How do you create a cron job?
- Use
crontab -e
to edit the cron table and add a job with a schedule and command.
- Use
What is a here document?
- A here document allows you to provide multiline input to a command or script:
cat <<EOFThis is a multiline string EOF
How do you handle whitespace in shell scripting?
- Enclose variables in quotes:
"$variable"
- Enclose variables in quotes:
How do you use
find
command in shell scripting?find
searches for files and directories:find /path -name "pattern"
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
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
How do you handle file permissions in a script?
- Use
chmod
to set permissions:chmod 755 file.sh
- Use
Advanced Topics
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
- A symbolic link (or symlink) is a file that points to another file or directory. Create one using
How do you perform arithmetic operations in shell scripting?
- Use
expr
,$((expression))
, orlet
for arithmetic operations. Example:result=$((5 + 3))
- Use
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
- A named pipe (FIFO) allows communication between processes. Create one with
What is the purpose of
getopts
?getopts
is used for parsing command-line options and arguments in scripts.
How do you use
getopts
for option parsing?while getopts ":a:b:" opt; docase ${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
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
- Environment variables are variables available to all processes in the environment. Set them using
How do you unset an environment variable?
- Use
unset
:unset VAR
- Use
What is
exec
used for in shell scripting?exec
replaces the shell with a specified command, not creating a new process:exec command
What is the purpose of
tee
command?tee
reads from standard input and writes to standard output and files:command | tee file.txt
What is
nohup
and how is it used?nohup
runs a command immune to hangups, with output redirected to a file:nohup command &
How do you schedule a script to run periodically?
- Use
cron
jobs. Edit withcrontab -e
and add a schedule:* * * * * /path/to/script.sh
- Use
What are
local
variables in shell functions?local
defines variables with scope limited to the function:function my_func {local var=value }
How do you debug a shell script?
- Use
set -x
to trace commands andset -e
to exit on errors. Also, you can usebash -x script.sh
for debugging.
- Use
What are
shell built-ins
?- Built-ins are commands built into the shell, such as
cd
,echo
,export
, andhistory
.
- Built-ins are commands built into the shell, such as
How do you use
find
to search for files and directories?- Example:
find /path -name "*.txt"
searches for.txt
files.
- Example:
How do you use
grep
to search for text within files?- Example:
grep "pattern" file.txt
searches forpattern
infile.txt
.
- Example:
What are
glob patterns
?- Globs are wildcards used for filename expansion, such as
*
,?
, and[]
.
- Globs are wildcards used for filename expansion, such as
How do you handle JSON data in a shell script?
- Use
jq
, a command-line JSON processor. Example:jq '.key' file.json
.
- Use
How do you manage permissions with
chmod
?- Use numeric (e.g.,
755
) or symbolic (e.g.,u+x
) modes to set permissions.
- Use numeric (e.g.,
What is the difference between
&&
and||
?&&
executes the second command if the first succeeds, while||
executes the second command if the first fails.
How do you use
xargs
to handle command-line arguments?xargs
converts input into arguments for a command. Example:echo "file1 file2" | xargs rm
.
How do you create and use
bash
arrays?arr=(one two three)echo ${arr[0]} # Outputs: one
What are
parameter expansions
in shell scripting?- Parameter expansions manipulate variable values. Example:
${var:-default}
provides a default value ifvar
is unset.
- Parameter expansions manipulate variable values. Example:
How do you use
read
with multiple variables?read var1 var2 <<< "value1 value2"What is
bash
arithmetic expansion?- It allows arithmetic calculations within scripts. Example:
result=$((5 + 3))
.
- It allows arithmetic calculations within scripts. Example:
How do you perform a substring extraction in
bash
?string="HelloWorld"substr=${string:5:5} # Outputs: World
How do you create a log file in a script?
- Redirect output to a log file:
command >> logfile.log 2>&1
.
- Redirect output to a log file:
What is a
debugging trap
?- A trap can be set to execute commands when a specific signal or condition occurs, useful for debugging.
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.
- Positional parameters are arguments passed to scripts. Use
How do you use
sed
to replace text?sed 's/old/new/g' file.txtHow do you use
awk
for simple text processing?awk '{print $1}' file.txtWhat is
shopt
inbash
?shopt
enables or disables shell options. Example:shopt -s nocaseglob
.
How do you check for command existence before running it?
- Use
command -v
ortype
:if command -v command_name >/dev/null 2>&1; then # command exists; fi
.
- Use
What is
exec
used for in file descriptors?exec
can redirect file descriptors. Example:exec 3>output.txt
opens file descriptor 3 for writing.
How do you use
find
to delete files?- Combine with
-exec
:find /path -name "*.tmp" -exec rm {} \;
.
- Combine with
How do you use
ps
andgrep
to find processes?- Combine them to search for processes:
ps aux | grep process_name
.
- Combine them to search for processes:
What is
diff
used for?diff
compares files line by line and shows differences.
How do you handle special characters in filenames?
- Use quotes or escape characters:
echo "file\$name"
orecho file\$name
.
- Use quotes or escape characters:
What is
basename
and how do you use it?basename
strips directory and suffix from filenames. Example:basename /path/to/file.txt .txt
.
How do you use
dirname
in shell scripting?dirname
strips the filename from a path, returning the directory. Example:dirname /path/to/file.txt
.
What is
printf
and how is it used?printf
formats and prints text. Example:printf "Name: %s\n" "John"
.
How do you use
eval
in shell scripting?eval
executes arguments as a shell command:eval "command with $var"
.
What is the
select
statement used for?select
creates a menu for user selection:select option in "Option1" "Option2"; do# process option done
How do you use
trap
to handle script termination?trap
executes commands when the script receives signals:trap 'commands' EXIT
.
What are
here documents
and how do you use them?- Provide multiline input directly in scripts:cat <<EOF
Multiline text EOF
- Provide multiline input directly in scripts:
How do you check for empty variables?
- Use conditional expressions:
if [ -z "$var" ]; then # variable is empty; fi
.
- Use conditional expressions:
What is the use of
cut
command?cut
extracts sections from lines of files:cut -d':' -f1 file.txt
.
How do you use
paste
to merge files?
-paste
merges lines of files side by side:paste file1.txt file2.txt
.What is
xargs
used for?
-xargs
builds and executes command lines from input:find . -name "*.txt" | xargs rm
.How do you use
sh
andbash
interchangeably?
-bash
is an enhanced version ofsh
. Usebash
for advanced features not available insh
.What is the
source
command?
-source
executes commands from a file in the current shell:source script.sh
.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.What is
basename
anddirname
commands?
-basename
strips the directory part of a filename,dirname
strips the file part, leaving the directory path.What is the difference between
&
andnohup
?
-&
runs a command in the background, whilenohup
makes the command immune to hangups, useful for background processes that need to persist.How do you use
ps
command to list processes?
-ps aux
lists all running processes with detailed information.How do you check the exit status of the last command?
- Use$?
, which holds the exit status of the last command executed.What are
shell options
and how do you manage them?
- Shell options control the behavior of the shell. Manage them usingshopt
andset
.How do you use
sed
for in-place editing of files?
- Use-i
option:sed -i 's/old/new/g' file.txt
.What is the difference between
>
and>>
redirection operators?
->
overwrites the file, while>>
appends to it.How do you handle complex command sequences?
- Use pipelines,&&
,||
, and grouping:(command1 && command2) || command3
.How do you create a tarball file?
- Usetar
command:tar -cvf archive.tar directory/
.How do you extract a tarball file?
- Usetar
command:tar -xvf archive.tar
.What is the
cut
command used for?
-cut
extracts specific columns or fields from files. Example:cut -d':' -f1 file.txt
.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.What is the
find
command for?
-find
searches for files and directories based on conditions. Example:find /path -type f -name "*.txt"
.How do you use
grep
to filter text?
- Example:grep "pattern" file.txt
searches forpattern
infile.txt
.How do you use
awk
for text processing?
-awk
processes and analyzes text. Example:awk '{print $1}' file.txt
prints the first field.What is the
date
command used for?
-date
displays or sets the system date and time. Example:date +"%Y-%m-%d"
formats the date.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.What is a
here document
?
- Ahere document
allows you to pass multiple lines of input to commands:cat <<EOFLine1 Line2 EOF
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
.How do you use
find
andxargs
together?
-find
can locate files, andxargs
can pass them to another command. Example:find /path -name "*.txt" | xargs wc -l
counts lines in all.txt
files.How do you use
grep
with regular expressions?
-grep
supports regular expressions for flexible text searching:grep '^pattern' file.txt
.How do you use
awk
to perform calculations?
-awk
can perform arithmetic operations:awk '{sum += $1} END {print sum}' file.txt
.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.How do you use
printf
for formatted output?
-printf
provides precise formatting:printf "Name: %-10s Age: %d\n" "John" 30
.How do you handle user input in shell scripts?
- Useread
to capture user input:read -p "Enter value: " variable
.What is
diff
used for?
-diff
compares two files line by line and shows differences.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.How do you create and use a symbolic link?
- Create withln -s target link_name
. Use the symlink as if it were the original file.What is the
alias
command used for?
-alias
creates shortcuts for commands. Example:alias ll='ls -la'
.How do you use
find
to execute commands on files?
- Example:find /path -name "*.log" -exec rm {} \;
finds and deletes.log
files.What are
trap
signals used for?
-trap
can handle signals and execute commands on script termination or other events.How do you use
ps
to monitor processes?
- Example:ps aux
lists all running processes with details.How do you use
ps
to find a process by name?
- Example:ps aux | grep process_name
.What is
shopt
and how is it used?
-shopt
sets and unsets shell options. Example:shopt -s nocaseglob
enables case-insensitive globbing.How do you use
grep
to search for text within a file?
- Example:grep "text" filename
searches fortext
infilename
.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.