Shell scripting provides an easy and powerful programming method to help you save time by automating a lot of your repeated manual tasks. Itโs a concept that can be vital for automation testers and DevOps engineers in interview preparations. So we came up with twenty frequently asked Shell scripting questions that you should prepare to answer during interviews.
Being a Shell script programmer, you should be aware of the different shells available on the Linux OS. And before even writing or executing a shell script, you must make sure that you are using the right Shell where the script is intended to run.
You should know that a script targeted for a particular Shell may not run in a different Shell without making appropriate changes. So keeping a tab on the Shell environment will help you avoid any hassle that could have appeared at runtime.
In the below set of Shell scripting questions and answers, weโve mostly used the BOURNE again shell or famously known as BASH. Also, if you are serious about preparing for a Linux interview, then do read the below posts to give full throttle to your preparations.
Now, you can continue reading the essential Shell scripting questions and examples given below.
Shell Scripting Questions forย Practice

Q-1. Presumably, what could be the reason that the <cat filename> command start giving the following error message?
--bash: cat: Command not found
Ans.
The command not found
ย error occurs when either the PATH variable is corrupt or has some issue in configuration.
Hence, itโll throw the error message as mentioned in the question.
Q-2. How can we pass arguments to a script in Linux? And how to access these arguments from within the script?
Ans.
We can write a bash script that can accept arguments from the command line in the following manner.
$ ./scriptName "arg1" "arg2"..."argn"
To access these arguments, we can use the positional parameters ($1 to $9) in the script. Each parameter corresponds to the position of the argument on the command line.
The first argument is read by the shell into the parameter $1, the second argument into $2, and so on. After $9, start enclosing the arguments in brackets like ${10}, ${11}, and ${12}.
Some shells donโt support the above method. In that case, to access parameters with numbers greater than 9, you can useย the shift command. It moves the parameter list to the left.
$1 is lost, $2 becomes $1, $3 becomes $2, and so on. The inaccessible 10th parameter becomes $9 and becomes accessible.
Letโs check out an example for clarity.
#!/bin/bash
# Call this script with at least 3 parameters
echo "First parameter is $1"
echo "Second parameter is $2"
echo "Third parameter is $3"
exit 0
Upon execution, the test script will yield the following output.
# sh parameters.sh 50 51 52
First parameter is 50
Second parameter is 51
Third parameter is 52
Q-3. What is the difference between $* and $@?
Ans.
$@ treats each quoted argument as separate arguments but $* considers the entire set of positional parameters as a single string.
Q-4. What is the command to display the list of files in a directory?
Ans.
The following command displays the list of files in a directory.
$ ls -lrt | grep ^-
Q-5. Write a shell script to display the last updated file or the newest file in a directory.
Ans.
Following is the test script to list the most recently changed file.
#!/bin/bash
ls -lrt | grep ^- | awk 'END{print $NF}'
Q-6. Print the current date, time, username, and current working directory.
Ans.
Letโs create a file named <stats.sh> and add the following code to it.
#!/bin/bash
echo "Hello, $LOGNAME"
echo "Current date is 'date'"
echo "User is 'who i am'"
echo "Current directory 'pwd'"
First of all, assign the execute permission for the script and then execute it. Itโll display the required information.
Q-7. Write a shell script that adds an extension โ.newโ to all the files in a directory.
Ans.
Please use the following script to change all the files in a directory to a โ.newโ extension. Kindly make sure to supply the directory name as an argument while running the test script.
#!/bin/bash
dir=$1
for file in `ls $1/*`
do
mv $file $file.new
done
Q-8. Write a shell script to print a number in reverse order. It should support the following requirements.
- The script should accept the input from the command line.
- If you donโt input any data, then display an error message to execute the script correctly.
Ans.
Letโs first, jot down the steps involved in the test script.
1. Suppose the input number is n.
2. Set reverse and single digits to 0 (i.e. rev=0, sd=0).
3.ย The expression (n % 10) will give the single leftmost digit i.e. sd.
4.ย To reverse the number, use this expression <rev * 10 + sd>.
5. Decrease the input number (n) by 1.
6.ย If n is greater than 0, then go to step no. 3. Else, execute step no. 7.
7. Printย theย result.
The script code is as follows.
#!/bin/bash
if [ $# -ne 1 ]
then
echo "Please provide the correct input in the below format."
echo "Usage: $0 number"
echo "ย ย ย ย ย ย This script will reverse the given number."
echo "ย ย ย ย ย ย For eg. $0 1234, will print 4321"
exit 1
fi
n=$1
rev=0
sd=0
while [ $n -gt 0 ]
do
sd=`expr $n % 10`
rev=`expr $rev \* 10ย + $sd`
n=`expr $n / 10`
done
echoย "Reverse number is $rev"
There are two ways in which we can run the above script.
Instance 1:
If there is no input, you will get the following output.
$ ./testscript.sh
Please provide the correct input in the below format.
Usage: ./testscript.sh number
This script will reverse the given number.
For eg. ./testscript.sh 1234, will print 4321
Instance 2:
When the input is available in the command line Argument, you will get the following output.
$ ./testscript.sh 12345
Reverse number is 54321
Q-9. How will you delete a file which has special characters in its file name?
Ans.
In Linux or Unix-like systems, you may come across file names including the following special characters, white spaces, backslashes, and more.
-
--
;
&
$
?
*
Bash shell considers most of the above special characters as commands. Thus, the โrmโ command may not be able to delete such files. The simplest way to delete files having special characters in their name is by using the inode number.
Step-1.
The <-i> option of the <ls> command displays the index number (inode) of each file.
$ ls -li
9966571 -rw-r--r-- 1 techbeamers users 0 Sep 16 10:05
Step-2.
Use the <find> command given below to delete the file, if it has an inode number such as 9966571.
$ find . -inum 9966571 -exec rm -i {} \;
Q-10. How to ask for input in a shell script from the terminal?
Ans:
In Linux, we can use the <read> command to take input from the user. It reads data from the terminal as the user enters it from the keyboard. And stores into a variable.
Letโs see a sample test script featuring the <read> command.
#!/bin/bash
echo โPlease enter your nameโ
read name
echo โMy Name is $nameโ
Upon running the above script, itโll prompt for the name and assigns the input value to the variable <name>.
$ ./test.sh
Please enter your name
TechBeamers
My Name is TechBeamers
Q-11. How can we perform numeric comparisons in Linux?
Ans.
The test command can perform variousย types of numeric comparisons using the following operators.
1. <eq>
Syntax: INTEGER1 -eq INTEGER2
Description: INTEGER1 is equal to INTEGER2
Example Code:
#!/bin/bash
read -p "Please enter number 20 from the keyboard : " n
if test $n -eq 20
then
ย ย ย echo "Thanks for entering the number 20."
else
ย ย echo โYou are not following my instructions.โ
fi
2. <ge>
Syntax: INTEGER1 -ge INTEGER2
Description: INTEGER1 is greater than or equal to INTEGER2
Example Code:
#!/bin/bash
read -p "Enter a number >= 10 : " n
if test $n -ge 10
then
ย ย ย echo "Correct value entered."
else
ย ย ย echo โYou are not following my instructions.โ
fi
3. <gt>
Syntax: INTEGER1 -gt INTEGER2
Description: INTEGER1 is greater than INTEGER2
Example Code:
#!/bin/bash
read -p "Enter number > 20 : " n
if test $n -gt 20
then
ย ย ย echo "$n is greater than 20."
else
ย ย ย echo โYou are not following my instructions.โ
fi
4. <le>
Syntax: INTEGER1 -le INTEGER2
Description: INTEGER1 is less than or equal to INTEGER2
Example Code:
#!/bin/bash
read -p "Enter backup level : " n
if test $n -le 6
then
ย ย ย echo "Incremental backup requested."
fi
if test $n -eq 7
then
ย ย ย echo "Full backup requested."
else
ย ย ย echo โYou are not following my instructions.โ
fi
5. <lt>
Syntax: INTEGER1 -lt INTEGER2
Description: INTEGER1 is less than INTEGER2
Example Code:ย ย ย
#!/bin/bash
read -p "Do not enter negative number here : " n
if test $n -lt 0
then
echo "You entered a negative number!!"
else
ย ย ย echo โYou are not following my instructions.โ
fi
6. <ne>
Syntax: INTEGER1 -ne INTEGER2
Description: INTEGER1 is not equal to INTEGER2
Example Code:
#!/bin/bash
read -p "Do not enter number 5 here : " n
if test $n -ne 5
then
ย ย ย echo "Thanks for not entering number 5."
else
ย ย ย echo โYou are not following my instructions.โ
fi
Q-12. What is the syntax for different types of loops available in shell scripting?
Ans.
Following are the loops supported in shell scripting.
1. <for loop>.
#!/bin/bash
for i in $( ls ); do
echo item: $i
done
2. <while loop>.
#!/bin/bash
COUNT=0
while [ $COUNT -lt 10 ]; do
echo The counter value is $COUNT
let COUNT+=1
done
3. <until loop>.
#!/bin/bash
COUNT=20
until [ $COUNT -lt 10 ]; do
echo The counter value is $COUNT
let COUNT-=1
done
4. <select loop>.
#!/bin/bash
PS3="Select a week day (1-7): "
select i in mon tue wed thur fri sat sun exit
do
ย case $i in
ย ย ย ย mon) echo "Monday";;
ย ย ย ย tue) echo "Tuesday";;
ย ย ย ย wed) echo "Wednesday";;
ย ย ย ย thur) echo "Thursday";;
ย ย ย ย fri) echo "Friday";;
ย ย ย ย sat) echo "Saturday";;
ย ย ย ย sun) echo "Sunday";;
ย ย ย ย exit) exit;;
ย esac
done
Q-13. How will you find the sum of all numbers in a file in Linux?
Ans.
Following is the script which computes the sum of all numbers stored in a file.
#!/bin/bash
awk '{x+=$0}END{print x}' filename
Q-14. Write a shell script to delete the lines containing a word <dd> if it appears between the 5th and 7th position.
Ans.
Letโs take a fixed-width file as:
ff1 ff2 ff3
sds dd fd
sd ss ew
dd dd se
The expected output after script execution is.
ff1 ff2 ff3
sd ss ew
The test script to do the expected task is as follows.
for i in 'cat test.txt'
do
j = 'expr length $i'
if [[ ( "$j" == 5 || "$j" == 7 ) ]]
then
v = 'echo $i | grep dd'
if [ "$v" != "" ]
then
echo $v
sed -i "s/$v/lalat/g" test.txt
fi
fi
done
Q-15. Find the unique words in a file and also count the occurrence of each of these words.
Ans.
$ cat animal.txt
tiger bear
elephant tiger bear
bear
The following test script/command will count the unique words.
$ awk '{for(i=1;i<=NF;i++)a[$i]++;}END{for(i in a){print i, a[i];}}' animal.txt
Output:
elephant 1
bear 3
tiger 2
Q-16. Get the total count of the word โLinuxโ in all the โ.txtโ files and also across files present in subdirectories.
Ans.
The following is the test script/command which recursively searches for the โ.txtโ files and returns the total occurrences of aย word <Linux>.
$ findย . -name *.txt -exec grep -c Linux '{}' \; | awk '{x+=$0;}END{print x}'
Q-17. Write a shell script to validate password strength.
Here are a few assumptions for the password string.
- Length ย โ minimum of 8 characters.
- Contain both alphabet and number.
- Include both the small and capital case letters.
If the password doesnโt comply with any of the above conditions, then the script should report it as a <Weak Password>.
Ans.
#Password Validation Script
echo "Enter your password"
read password
len="${#password}"
if test $len -ge 8 ; then
echo "$password" | grep -q [0-9]
if test $? -eq 0 ; then
echo "$password" | grep -q [A-Z]
if test $? -eq 0 ; then
echo "$password" | grep -q [a-z]
if test $? -eq 0 ; then
echo "Strong Password"
else
echo "Weak Password -> Should include a lower case letter."
fi
else
echo "Weak Password -> Should include a capital case letter."
fi
else
echo "Weak Password -> Should use numbers in your password."
fi
else
echo "Weak Password -> Password length should have at least 8 characters."
fi
Q-18. Write a shell script to print the count of files and subdirectories in the specified directory.
Ans.
#!/bin/bash
if [ -d "$@" ]; then
echo "Files found: $(find "$@" -type f | wc -l)"
echo "Folders found: $(find "$@" -type d | wc -l)"
else
echo "[ERROR] Please retry with a folder."
exit 1
fi
Q-19. Print the reverse of an input number using a script.
Ans.
#!/bin/bash
if [ $# -eq 1 ]; then
if [ $1 -gt 0 ]; then
num=$1
revNum=0
while [ $num -ne 0 ]
do
testnum=$(( $num % 10 ))
revNum=$(( $revNum * 10 + $testnum ))
num=$(( $num / 10 ))
done
echo "Reverse Number: $revNum of $1"
else
echo "Input is less than 0, retry with a different number."
fi
else
echo "ERROR: Retry with one parameter."
fi
Q-20. Reverse the list of strings and reverse each string further in the list.
Ans.
#!/bin/bash
if [ $# != 0 ]; then
len=`echo $@ | wc -c`
len=`expr $len - 1`
strrev=""
while test $len -gt 0
do
strrev1=`echo $@ | cut -c$len`
strrev=$strrev$strrev1
len=`expr $len - 1`
done
echo $strrev
else
echo "ERROR: Retry with a list of strings."
fi
Summary โ Essential Shell Scripting Questions and Answers
We are hopeful that the above essential Shell scripting questions and answersย would help you immensely.ย If youโve any questions, then please feel free toย let us know about it.
Lastly, if you enjoyed the post, then please care to share it with friends and on social media.
Keep Learning,
TechBeamers