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
chmodcommand:chmod +x script.sh
- Use the
What does the
#!/bin/bashline 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.shif 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_nameor${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
readonlyto 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
ifstatement in shell scripting?if [ condition ]; then# commands elif [ other_condition ]; then # other commands else # default commands fiWhat is the purpose of the
testcommand?testis used to evaluate expressions, commonly for checking file attributes or string conditions.
How do you write a
forloop in shell scripting?for variable in list; do# commands doneHow do you write a
whileloop in shell scripting?while [ condition ]; do# commands doneWhat is a
casestatement?- A
casestatement 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
returnin functions?returnis 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.txtHow 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 fiWhat is the difference between
-eand-fin file tests?-echecks if a file exists,-fchecks 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.txtorcommand >> 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
trapused for?trapallows 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.?$0is 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; command2orcommand1 && command2
- Use
What is the
execcommand used for?execreplaces the shell with the specified command, without creating a new process.
How do you debug a shell script?
- Use
set -xto enable debugging andset +xto disable it.bash -x script.shalso works.
- Use
What is the difference between
sourceand.?- Both
sourceand.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 -eto 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 EOFHow do you handle whitespace in shell scripting?
- Enclose variables in quotes:
"$variable"
- Enclose variables in quotes:
How do you use
findcommand in shell scripting?findsearches for files and directories:find /path -name "pattern"
What is
awkand how is it used?awkis a powerful text processing tool used for pattern scanning and reporting. Example:awk '{print $1}' file.txt
What is
sedand how is it used?sedis 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
chmodto 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)), orletfor 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?getoptsis used for parsing command-line options and arguments in scripts.
How do you use
getoptsfor 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 doneWhat 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
execused for in shell scripting?execreplaces the shell with a specified command, not creating a new process:exec command
What is the purpose of
teecommand?teereads from standard input and writes to standard output and files:command | tee file.txt
What is
nohupand how is it used?nohupruns a command immune to hangups, with output redirected to a file:nohup command &
How do you schedule a script to run periodically?
- Use
cronjobs. Edit withcrontab -eand add a schedule:* * * * * /path/to/script.sh
- Use
What are
localvariables in shell functions?localdefines variables with scope limited to the function:function my_func {local var=value }
How do you debug a shell script?
- Use
set -xto trace commands andset -eto exit on errors. Also, you can usebash -x script.shfor 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
findto search for files and directories?- Example:
find /path -name "*.txt"searches for.txtfiles.
- Example:
How do you use
grepto search for text within files?- Example:
grep "pattern" file.txtsearches forpatterninfile.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
xargsto handle command-line arguments?xargsconverts input into arguments for a command. Example:echo "file1 file2" | xargs rm.
How do you create and use
basharrays?arr=(one two three)echo ${arr[0]} # Outputs: oneWhat are
parameter expansionsin shell scripting?- Parameter expansions manipulate variable values. Example:
${var:-default}provides a default value ifvaris unset.
- Parameter expansions manipulate variable values. Example:
How do you use
readwith multiple variables?read var1 var2 <<< "value1 value2"What is
basharithmetic 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: WorldHow 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 parametersand 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
sedto replace text?sed 's/old/new/g' file.txtHow do you use
awkfor simple text processing?awk '{print $1}' file.txtWhat is
shoptinbash?shoptenables or disables shell options. Example:shopt -s nocaseglob.
How do you check for command existence before running it?
- Use
command -vortype:if command -v command_name >/dev/null 2>&1; then # command exists; fi.
- Use
What is
execused for in file descriptors?execcan redirect file descriptors. Example:exec 3>output.txtopens file descriptor 3 for writing.
How do you use
findto delete files?- Combine with
-exec:find /path -name "*.tmp" -exec rm {} \;.
- Combine with
How do you use
psandgrepto find processes?- Combine them to search for processes:
ps aux | grep process_name.
- Combine them to search for processes:
What is
diffused for?diffcompares 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
basenameand how do you use it?basenamestrips directory and suffix from filenames. Example:basename /path/to/file.txt .txt.
How do you use
dirnamein shell scripting?dirnamestrips the filename from a path, returning the directory. Example:dirname /path/to/file.txt.
What is
printfand how is it used?printfformats and prints text. Example:printf "Name: %s\n" "John".
How do you use
evalin shell scripting?evalexecutes arguments as a shell command:eval "command with $var".
What is the
selectstatement used for?selectcreates a menu for user selection:select option in "Option1" "Option2"; do# process option done
How do you use
trapto handle script termination?trapexecutes commands when the script receives signals:trap 'commands' EXIT.
What are
here documentsand 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
cutcommand?cutextracts sections from lines of files:cut -d':' -f1 file.txt.
How do you use
pasteto merge files?
-pastemerges lines of files side by side:paste file1.txt file2.txt.What is
xargsused for?
-xargsbuilds and executes command lines from input:find . -name "*.txt" | xargs rm.How do you use
shandbashinterchangeably?
-bashis an enhanced version ofsh. Usebashfor advanced features not available insh.What is the
sourcecommand?
-sourceexecutes commands from a file in the current shell:source script.sh.How do you use
cutto extract fields from a file?
- Example:cut -d',' -f1 file.csvextracts the first field from a CSV file.What is
basenameanddirnamecommands?
-basenamestrips the directory part of a filename,dirnamestrips the file part, leaving the directory path.What is the difference between
&andnohup?
-&runs a command in the background, whilenohupmakes the command immune to hangups, useful for background processes that need to persist.How do you use
pscommand to list processes?
-ps auxlists 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 optionsand how do you manage them?
- Shell options control the behavior of the shell. Manage them usingshoptandset.How do you use
sedfor in-place editing of files?
- Use-ioption: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?
- Usetarcommand:tar -cvf archive.tar directory/.How do you extract a tarball file?
- Usetarcommand:tar -xvf archive.tar.What is the
cutcommand used for?
-cutextracts specific columns or fields from files. Example:cut -d':' -f1 file.txt.How do you use
chmodto set file permissions?
- Example:chmod 755 file.shsets read, write, and execute permissions for the owner, and read and execute for others.What is the
findcommand for?
-findsearches for files and directories based on conditions. Example:find /path -type f -name "*.txt".How do you use
grepto filter text?
- Example:grep "pattern" file.txtsearches forpatterninfile.txt.How do you use
awkfor text processing?
-awkprocesses and analyzes text. Example:awk '{print $1}' file.txtprints the first field.What is the
datecommand used for?
-datedisplays 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 documentallows you to pass multiple lines of input to commands:cat <<EOFLine1 Line2 EOFWhat is
sedand how is it used for text processing?
-sedis a stream editor for filtering and transforming text. Example:sed 's/old/new/g' file.txt.How do you use
findandxargstogether?
-findcan locate files, andxargscan pass them to another command. Example:find /path -name "*.txt" | xargs wc -lcounts lines in all.txtfiles.How do you use
grepwith regular expressions?
-grepsupports regular expressions for flexible text searching:grep '^pattern' file.txt.How do you use
awkto perform calculations?
-awkcan perform arithmetic operations:awk '{sum += $1} END {print sum}' file.txt.What is the
cutcommand used for?
-cutextracts sections from lines of files. Example:cut -d',' -f1 file.csvextracts the first field from a CSV file.How do you use
printffor formatted output?
-printfprovides precise formatting:printf "Name: %-10s Age: %d\n" "John" 30.How do you handle user input in shell scripts?
- Usereadto capture user input:read -p "Enter value: " variable.What is
diffused for?
-diffcompares two files line by line and shows differences.How do you use
xargsfor processing large numbers of arguments?
-xargsbuilds and executes command lines from input. Example:find /path -type f | xargs rmremoves 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
aliascommand used for?
-aliascreates shortcuts for commands. Example:alias ll='ls -la'.How do you use
findto execute commands on files?
- Example:find /path -name "*.log" -exec rm {} \;finds and deletes.logfiles.What are
trapsignals used for?
-trapcan handle signals and execute commands on script termination or other events.How do you use
psto monitor processes?
- Example:ps auxlists all running processes with details.How do you use
psto find a process by name?
- Example:ps aux | grep process_name.What is
shoptand how is it used?
-shoptsets and unsets shell options. Example:shopt -s nocaseglobenables case-insensitive globbing.How do you use
grepto search for text within a file?
- Example:grep "text" filenamesearches fortextinfilename.What are
file descriptorsand how do you use them?
- File descriptors are integer handles for files and input/output. Example:exec 3>file.txtopens 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.

