This guide covers commonly used shell commands and sample shell scripting interview questions with solutions. Ideal for beginners and professionals preparing for Linux or DevOps interviews.
- Commonly Used Shell Commands
- List All Running Processes
- Filter Only Process IDs
- Fetch and Filter Remote Logs
- Script: Numbers Divisible by 3 and 5 but Not 15
- Best Practices During Interview
| Command/Concept | Purpose / Description |
|---|---|
awk |
Powerful text processing and pattern scanning tool |
sed |
Stream editor for transforming text (search/replace, insertion, deletion) |
xargs |
Build and execute command lines from standard input |
cut |
Extract sections from each line of input (e.g., specific columns) |
sort |
Sort lines of text |
uniq |
Filter out repeated lines (often combined with sort) |
tee |
Read from stdin and write to stdout and files simultaneously |
find |
Search for files and directories based on conditions |
grep -r |
Recursive search through files for matching patterns |
trap |
Catch signals (e.g., SIGINT) to perform cleanup or other actions |
getopts |
Parse command-line options and arguments in scripts |
printf |
Formatted output (more powerful than echo) |
test / [ ] |
Conditional expressions |
expr |
Evaluate expressions (arithmetic, string operations) |
diff |
Compare files line by line |
curl / wget |
Download files or interact with web APIs |
jq |
Parse and manipulate JSON data (if installed) |
rsync |
Efficient file synchronization and transfer |
cron |
Schedule periodic execution of scripts |
ssh |
Run commands on remote machines |
xclip / pbcopy |
Copy output to clipboard (Linux / macOS) |
basename / dirname |
Extract filename or directory path components |
mktemp |
Create temporary files or directories safely |
read |
Read user input in scripts |
while / for loops |
Looping constructs |
case |
Multi-branch conditional statements |
>&, 2>&1 |
Redirect stdout and stderr |
exec |
Replace shell with a command or redirect file descriptors |
set -e |
Exit script immediately on error |
set -u |
Treat unset variables as errors |
set -x |
Debug: print commands and their arguments as they execute |
basename |
Strip directory and suffix from file name |
date |
Format or display date/time |
sleep |
Pause execution for a specified time |
tee |
Split output to file and screen |
logger |
Write messages to syslog |
getent |
Query system databases (passwd, hosts, services) |
Answer: Use the shebang #! followed by the path to the interpreter.
#!/bin/bash
echo "Script running"Answer: Assign using = and print with echo.
greeting="Hello"
echo "$greeting"Answer: Command substitution.
time_now=$(date)
echo "Current time: $time_nowAnswer: Use the read command.
echo "Enter your age:"
read age
echo "Your age is $age"Answer: It indicates the success (0) or failure (non-zero) of the last executed command.
ls /nonexistent
echo $? # Output: non-zero (failure)Answer: Use if, elif, else, and fi.
if [ -d "/path/to/dir" ]; then
echo "Directory exists"
else
echo "Directory does not exist"
fiAnswer: To repeatedly execute commands.
for file in *.txt; do
echo "File: $file"
doneAnswer: Use the # symbol.
# This is a comment
echo "Code execution"Answer: Parameters are accessed using $1, $2, etc.
echo "First parameter: $1"Answer: Use single quotes to prevent variable expansion and double quotes to allow it.
var="world"
echo 'Hello $var' # Output: Hello $var
echo "Hello $var" # Output: Hello worldAnswer: Use -e in a conditional statement.
if [ -e "myfile.txt" ]; then
echo "File exists"
fiAnswer: To handle multiple conditions.
case "$1" in
start) echo "Starting";;
stop) echo "Stopping";;
*) echo "Unknown option";;
esacAnswer: Use a while loop with read.
while IFS= read -r line; do
echo "Line: $line"
done < "file.txt"Answer: Use > for overwrite and >> for append.
echo "Hello, World!" > output.txtAnswer: Use the grep command.
grep "search_term" file.txtAnswer: Use functions.
greet() {
echo "Hello, $1"
}
greet "Alice"Answer: Use the export command.
export PATH=$PATH:/new/pathAnswer: Use ls -l or test flags like -r, -w, and -x.
if [ -r "file.txt" ]; then
echo "File is readable"
fiAnswer: Use exit or set -e.
set -e
cp nonexistentfile /somewhere
echo "This won't be printed"Answer: It shifts the positional parameters to the left.
echo "$1"
```shift
echo "$1"Answer: Concatenate them directly.
greeting="Hello"
name="Alice"
full_greeting="$greeting, $name"
echo "$full_greeting"Answer: Use the dirname command.
path="/home/user/file.txt"
echo $(dirname "$path")Answer: Use expr or $(( )).
sum=$((3 + 5))
echo "Sum: $sum"Answer: To change shell options and positional parameters.
set -x # Enable debuggingAnswer: Use the -d flag in a conditional statement.
if [ -d "/path/to/dir" ]; then
echo "Directory exists"
fiAnswer: Use the cut command.
echo "name:age:location" | cut -d ':' -f 2Answer: Use the sed command.
sed -i 's/old_text/new_text/g' file.txtAnswer: To repeat commands until a condition is true.
counter=1
until [ $counter -gt 5 ]; do
echo "Counter: $counter"
counter=$((counter + 1))
doneAnswer: Use command substitution.
current_user=$(whoami)
echo "Current user: $current_user"Answer: Reads from standard input and writes to standard output and files.
echo "Hello, World!" | tee output.txtAnswer: Use a conditional statement with * wildcard.
string="Hello, World!"
if [[ "$string" == *"World"* ]]; then
echo "Substring found"
fiAnswer: For formatted output.
printf "Name: %s, Age: %d\n" "Alice" 30Answer: Use the IFS variable.
string="a,b,c"
IFS=',' read -r -a array <<< "$string"
echo "${array[0]}"Answer: Use the basename command.
path="/home/user/file.txt"
echo $(basename "$path")Answer: Use -z in a conditional statement.
if [ -z "$string" ]; then
echo "String is empty"
fiAnswer: Prints the current working directory.
echo "Current directory: $(pwd)"Answer: Use sed or parameter expansion.
string=" Hello, World! "
trimmed=$(echo "$string" | sed 's/^ *//;s/ *$//')
echo "$trimmed"Answer: To catch signals and execute commands when they occur.
trap "echo 'Interrupted!'; exit" INTAnswer: Use = or != inside [[ ]] or [ ].
str1="hello"
str2="world"
if [ "$str1" = "$str2" ]; then
echo "Strings are equal"
else
echo "Strings are not equal"
fiAnswer: Use command -v or which.
if command -v git >/dev/null 2>&1; then
echo "Git is installed"
else
echo "Git is not installed"
fiAnswer: Use $#.
echo "Number of arguments: $#"Answer: Use the ln -s command.
ln -s /path/to/original /path/to/linkAnswer: Use command substitution with cat.
file_content=$(cat file.txt)
echo "$file_content"Answer: Use &&.
if [ -f "file1" ] && [ -f "file2" ]; then
echo "Both files exist"
fiAnswer: Use ||.
if [ -f "file1" ] || [ -f "file2" ]; then
echo "At least one file exists"
fiAnswer: Use -z or -n.
if [ -n "$var" ]; then
echo "Variable is set"
fiAnswer: Use parameter expansion.
str="Hello, World!"
new_str=${str/World/```shell}
echo "$new_str"Answer: Use tr.
str="HELLO"
lower=$(echo "$str" | tr 'A-Z' 'a-z')
echo "$lower"Answer: Use tr.
str="hello"
upper=$(echo "$str" | tr 'a-z' 'A-Z')
echo "$upper"Answer: Use $RANDOM.
echo "Random number: $RANDOM"Answer: Use arithmetic expansion.
num=4
if ((num % 2 == 0)); then
echo "Even"
else
echo "Odd"
fiAnswer: Use the head command.
head -n 10 file.txtAnswer: Use the tail command.
tail -n 10 file.txtAnswer: Use wc -l.
wc -l < file.txtAnswer: Use wc -w.
wc -w < file.txtAnswer: Use grep -rl.
grep -rl "search_text" /path/to/dirAnswer: Use the printenv command.
printenvAnswer: Use the cd command.
cd /path/to/dirAnswer: Use the seq command.
seq 1 10Answer: Use the sleep command.
sleep 5Answer: Use the file command.
file filenameAnswer: Use the sort and uniq commands.
sort file.txt | uniqAnswer: Use the sort command.
sort file.txtAnswer: Use the cat command.
cat file1.txt file2.txt > merged.txtAnswer: Use the du command.
du -```sh /path/to/dirAnswer: Use the df command.
df -hAnswer: Use the ps command.
ps auxAnswer: Use the pkill command.
pkill process_nameAnswer: Use the pidof command.
pidof process_nameAnswer: Use the systemctl command.
systemctl status service_nameAnswer: Use the systemctl start command.
systemctl start service_nameAnswer: Use the systemctl stop command.
systemctl stop service_nameAnswer: Use the systemctl enable command.
systemctl enable service_nameAnswer: Use the systemctl disable command.
systemctl disable service_nameAnswer: Use the hostname command.
hostnameAnswer: Use the hostnamectl command.
hostnamectl set-hostname new_hostnameAnswer: Use the date command.
dateAnswer: Use the date command with appropriate options.
date MMDDhhmm[[CC]YY][.ss]Answer: Use the useradd command.
useradd usernameAnswer: Use the userdel command.
userdel usernameAnswer: Use the groupadd command.
groupadd groupnameAnswer: Use the groupdel command.
groupdel groupnameAnswer: Use the usermod -aG command.
usermod -aG groupname usernameAnswer: Use the groups command.
groups usernameAnswer: Use the chown command.
chown user:group file.txtAnswer: Use the chmod command.
chmod 755 file.txtAnswer: Use the chown -R command.
chown -R user:group /path/to/dirAnswer: Use the chmod -R command.
chmod -R 755 /path/to/dirAnswer: Use the tar command.
tar -cvf archive.tar /path/to/dirAnswer: Use the tar command.
tar -xvf archive.tarAnswer: Use the gzip command.
gzip file.txtAnswer: Use the gunzip command.
gunzip file.txt.gzAnswer: Use the tar command with compression options.
tar -czvf archive.tar.gz /path/to/dirAnswer: Use the tar command with decompression options.
tar -xzvf archive.tar.gzAnswer: Use the diff command.
diff file1.txt file2.txtAnswer: Use the head command.
head -n 5 file.txtAnswer: Use the tail command.
tail -n 5 file.txtAnswer: Use the which command.
which bashAnswer: Use the --version option.
bash --versionAnswer: Use the cal command.
cal 12 2023The purpose of this documentation is to document common interview questions and answers about Linux shell script.
- Q1: What is Shell?
- Q2: What is a Shell Script? Can you name some of its advantages?
- Q3: What are the different types of variables used in Shell Script?
- Q4: How do you create a shortcut in Linux?
- Q5: What are the various stages of a Linux process it passes through?
- Q6: How to pass an argument to a script?
- Q7: How to calculate the number of passed arguments?
- Q8: How to get script name inside a script?
- Q9: How to check if the previous command was run successfully?
- Q10: How to get the last line from a file using just the terminal?
- Q11: When debugging a Bash script, what command would you use to stop the execution of the program until the Enter key is pressed?
- Q12: How to get the first line from a file using just the terminal?
- Q13: How to get the first line from a file using just the terminal?
- Q14: How to redirect both standard output and standard error to the same location?
- Q15: What is difference between ‘ and ” quotes?
- Q16: What is the difference between $* and $@?
- Q17: Write down the Syntax for all the loops in Shell Scripting.
- Q18: When should shell programming/scripting not be used?
- Q19: What are the default permissions of a file when it is created?
- Q20: Determine the output of the following command:
- Q21: Determine the output of the following command:
- Q22: Determine the output of the following command:
- Q23: How booleans are used in a shell script?
- Q24: How to get part of string variable with echo command only?
- Q25: How to print all the arguments provided to the script?
- Q26: How to print PID of the current shell?
- Q27: How to print all array elements and their respective indexes?
- Q28: How to print the first array element?
- Q29: How many fields are present in a crontab file and what does each field specify?
- Q30: How to debug the problems encountered in the shell script/program?
- Q31: How to declare a readlone variable?
- Q32: What are the different commands available to check the disk usage?
- Q33: What is the commands to check a directory space usage?
- Q34: How to open a read-only file in the Shell?
- Q35: Write a shell script to get current date, time, user name, file name and working directory?
- Q36: How to find all the files modified in less than 7 days?
- Q37: Print a given number, in reverse order using a Shell script such that the input is provided using command Line Argument only.
- Q38: How to calculate a real number calculation in shell script?
- Q39: How to get the value of pi till a 20 decimal places?
- Q40: Write a script to print the first 10 elements of Fibonacci series.
- Q41: What is the difference between $$ and $!?
- Q42: What are zombie processes?
- Q43: Print the 10th line without using tail and head command.
- Q44: How will you find the total disk space used by a specific user?
- Q45: Find all the files modified in less than 2 days and print the record count of each.
- Q46: How to send a mail with a compressed file as an attachment?
What is Shell?
The Shell is a Command Line Interpreter. It translates commands entered by the user and converts them into a language that is understood by the Kernel. The shell interprets a command typed in at the terminal, and calls the program that you want.
What is a Shell Script? Can you name some of its advantages?
A shell script is a command-containing text-file that contains commands in order of their execution. Typical operations performed by shell scripts include printing text, file manipulation, and program execution.
Following are the two main advantages of shell scripting:
- It facilitates developing your own custom OS with relevant features which best suit your needs.
- It facilitates designing software applications according to their respective platforms.
What are the different types of variables used in Shell Script?
A shell script has two types of variables :
- System-defined variables are created/defined by the Operating System(Linux) itself. These variables are generally defined in Capital Letters and can be viewed by “set” command.
- User-defined variables are created or defined by system users and the values of variables can be viewed by using the command “echo”.
How do you create a shortcut in Linux?
This can be done with the help of links present in Linux OS.
- Hard Link: Hard links are linked to the inode of the file and have to be on the same file system as of the file. Deleting the original file does not affect the hard link.
- Soft Link: Soft links are linked to the file name and can reside on a different file system as well. Deleting the original file makes the soft link inactive.
What are the various stages of a Linux process it passes through?
A Linux process generally passes through four stages:
- Waiting: The Linux process waits for the resource.
- Running: The Linux process is currently being executed.
- Stopped: The Linux process is stopped after successful execution.
- Zombie: The process has stopped but is still active in the process table.
How to pass an argument to a script?
# cat test.sh
#!/usr/bin/env bash
echo ${1}
# bash test.sh p1
p1How to calculate the number of passed arguments?
# cat test.sh
#!/usr/bin/env bash
echo "Number of Parameters passed:$#"
# ./test.sh p1 p2 p3 p4
Number of Parameters passed:4How to get script name inside a script?
# cat test.sh
#!/usr/bin/env bash
echo "Script Name:$0"
# ./test.sh
Script Name:./test.shHow to get script name inside a script?
# cat test.sh
#!/usr/bin/env bash
var=$?
if var=0 ;then
echo "Script was Run successfully!"
else
echo "Script was Run failed!"
fi
# ./test.sh
Script was Run successfully!How to get the last line from a file using just the terminal?
# tail -1 /var/log/messages
Oct 18 03:42:46 ke-ol7vm1 nm-dispatcher: req:1 'dhcp4-change' [eth0]: start running ordered scripts...When debugging a Bash script, what command would you use to stop the execution of the program until the Enter key is pressed?
read
How to get the first line from a file using just the terminal?
# head -1 /var/log/boot.log-20190716
[ OK ] Started Show Plymouth Boot Screen.How to get the 3rd element/column from each line from a file?
# cat test.sh
#!/usr/bin/env bash
cat > test.txt <<EOF
col11 col12 col13 col14 col15
col21 col22 col23 col24 col25
col31 col32 col33 col34 col35
EOF
awk '{print $3}' ${1}
# ./test.sh test.txt
col13
col23
col33How to redirect both standard output and standard error to the same location?
The two methods to redirect standard output and standard error to the same location are the following;
2>&1(# ls /usr/share/doc > out.txt 2>&1 )
&>(# ls /usr/share/doc &> out.txt )What differentiate between ‘ and ” quotes?
- Single Quotes: Used in case evaluation of variables to values is undesired.
- Double Quotes: Used in case evaluation of variables to values is required.
What is the difference between $ and $@?*
Write down the Syntax for all the loops in Shell Scripting.
For Loop:
for var in word1 word2 ... wordN
do
Statement(s) to be executed for every word.
doneWhile Loop:
while command
do
Statement(s) to be executed if command is true
doneUntil Loop:
until command
do
Statement(s) to be executed until command is true
doneWhen should shell programming/scripting not be used?
It is not advisable to use Shell scripting in the following cases;
- When the task is very much complex, e.g. writing the entire payroll processing system.
- Where there is a high degree of productivity required.
- When it needs or involves different software tools.
What are the default permissions of a file when it is created?
On Linux and other Unix-like operating systems, new files are created with a default set of permissions. The umask or user mask command is used to determine the default permissions for newly created files. It is a 4-digit Octal number which is set and expressed using symbolic values. The default permission of a file when it is created is 664 i.e. rw-rw-r-. The table for file permissions is given below;
| 0 | 0 | No permissions |
|---|---|---|
| 1 | 1 | execute |
| 2 | 2 | write |
| 3 | 1+2 | execute + write |
| 4 | 4 | read |
| 5 | 1+4 | execute + read |
| 6 | 2+4 | write + read |
| 7 | 1+2+4 | execute + write + read |
Determine the output of the following command: $ name=Bob && echo 'My name is ${name}'
$ name=Bob && echo 'My name is ${name}'
My name is ${name}Determine the output of the following command: $ [ -z "" ] && echo true || echo false
$ [ -z "" ] && echo true || echo false
trueDetermine the output of the following command: $ echo ${new:-variable}
$ echo ${new:-variable}
variableHow booleans are used in a shell script?
In bash, true is 0 and false is any value but 0. There exist two commands, true and false that deliver true or false, respectively:
$ true; echo $?
0
$ false; echo $?
1#!/usr/bin/env bash
#bool.sh
bool=true
if ($bool);then
echo true
fi
bool=false
if !($bool);then
echo false
fi
$ ./bool.sh
true
false
How to get part of string variable with echo command only?
To extract substrings in a shell script is to use a Bash variable with the substring syntax, just likes python slice.
#!/usr/bin/env bash
#echo ${var:x:y}
#x - start position
#y - length
var="My name is Bob, and I work at Oracle."
#From left extract string
echo ${var:11:3} # will display Bob
echo ${var::2} # will display My
echo ${var:19} # will display I work at Oracle.
#From right extract string
echo ${var:0-7:6} # will display Oracle
echo ${var:0-7} # will display Oracle.How to print all the arguments provided to the script?
#!/usr/bin/env bash
for i;do echo $i ;done
# ./test.sh a b c d e f
a
b
c
d
e
fHow to print PID of the current shell?
#!/usr/bin/env bash
for PID in $$; do
echo ${PID}
done
# ./test.sh
3950How to print all array elements and their respective indexes?
#!/usr/bin/env bash
array=("This" "is" "a" "test")
echo "Array elements:${array[@]}"
echo "Array element index:${!array[@]}"
# ./test.sh
Array elements:This is a test
Array element index:0 1 2 3How to print the first array element?
#!/usr/bin/env bash
array=("This" "is" "Shell" "Scripting" )
echo "First element:${array[0]}"
echo "All elements:${array[@]}"
$ ./test.sh
First element:This
All elements:This is Shell ScriptingHow many fields are present in a crontab file and what does each field specify?
The crontab file has six fields. The first five fields contain information on when to execute the command and they are as follows;
- minute(0-59)
- hour(0-23)
- day(1-31)
- month(1-12)
- day of the week(0-6, Sunday = 0).
The sixth field contains the command to be executed.
How to debug the problems encountered in the shell script/program?
Given below are some common methods used to debug the problems in the script.
- Debug statements can be inserted in the shell script to output/display the information which helps to identify the problem.
- Using set -x we can enable debugging in the script.
How to declare a readlone variable?
#!/usr/bin/env bash
declare -r var1=1
echo "var1 = $var1" # var1 = 1
(( var1++ )) # x.sh: line 4: var1: readonly variableHow to declare a readlone variable?
There are three different commands available to check the disk usage.
- df: It is used to check the free disk space.
- du: It is used to check the directory wise disk usage.
- dfspace: It is used to check the free disk space in terms of MB.
What is the commands to check a directory space usage?
[ke@ke-linux ~]$ du -s ~ -m
1501 /home/keHow to open a read-only file in the Shell?
A read-only file can be opened using the below command:
#vi –R <File Name> Write a shell script to get current date, time, user name, file name and working directory.
#!/usr/bin/env bash
echo "Hello, $LOGNAME"
echo "Today's date is `date`"
echo "Username is `who i am`"
echo "Current file name is $0"
echo "Current directory is `pwd`"
$ ./test.sh
Hello, ke
Today's date is 2019年 10月 26日 星期六 19:46:46 CST
Username is ke pts/0 2019-10-26 19:41 (10.0.2.2)
Current file name is ./test.sh
Current directory is /home/keHow to find all the files modified in less than 7 days?
$ find . -type f -mtime -7 -exec ls -l {} \;Print a given number, in reverse order using a Shell script such that the input is provided using command Line Argument only.
#!/usr/bin/env bash
Usage(){
echo "Usage: $0 number"
echo " Reverse of the given number will be printed"
echo " For eg. $0 0123, 3210 will be printed"
exit 1
}
[ $# -ne 1 ] && Usage
n=$1
rev=0
sd=0
while [ $n -gt 0 ]
do
sd=$(( n % 10 ))
rev=$(( rev * 10 + sd ))
n=$(( n / 10 ))
done
echo "Reverse results:$rev"
[ke@ke-linux ~]$ ./test.sh 12345
Reverse results:54321
[ke@ke-linux ~]$ ./test.sh 123456789
Reverse results:987654321How to calculate a real number calculation in shell script?
$ echo "1.6+2.5" | bc
4.1
$ echo "1.6*2.5" | bc
4.0
$ echo "scale=3;3/2" | bc
1.500
$ echo "scale=2;1.6^2" | bc
2.56
$ echo "scale=2;sqrt(2.56)" | bc
1.60How to get the value of pi till a 20 decimal places?
$ echo -n "π=";echo "scale=20; 4*a(1)" | bc -l
π=3.14159265358979323844Write a script to print the first 10 elements of Fibonacci series.
#!/usr/bin/env bash
for i in {1..10}; do
if [[ ${i} -eq 1 || ${i} -eq 2 ]]; then
a=1
b=1
echo 1
else
c=$b
b=$((a + b))
a=$c
echo $b
fi
done
$ ./test.sh
1
1
2
3
5
8
13
21
34
55
What is the difference between $$ and $!?
$$ gives the process id of the currently executing process whereas $! Shows the process id of the process that recently went into the background.
What are zombie processes?
These are the processes which have died but whose exit status is still not picked by the parent process. These processes even if not functional still have its process id entry in the process table.
Print the 10th line without using tail and head command.
#!/usr/bin/env bash
sed –n '10p' file1How will you find the total disk space used by a specific user?
#!/usr/bin/env bash
du -s /home/<user home path>Find all the files modified in less than 2 days and print the record count of each.
$ find . –mtime -2 –exec wc –l {} \; How to send a mail with a compressed file as an attachment?
$ zip file1.zip file1 | mailx –s "subject" <Recipients email id>
Email content
EOF