Linux Shell Scripting Interview Questions

How to pass argument to a script ?

./script argument
Example : Script will show filename
./ file1.txt
cat $1

How to use argument in a script ?

First argument: $1,
Second argument : $2
Example : Script will copy file (arg1) to destination (arg2)
./ file1.txt /tmp/
cp $1 $2

How to calculate number of passed arguments ?


How to get script name inside a script ?


How to check if previous command run successful ?


How to get last line from a file ?

tail -1

How to get first line from a file ?

head -1

How to get 3rd element from each line from a file ?

awk ‘{print $3}’

How to get 2nd element from each line from a file, if first equal FIND?

awk ‘{ if ($1 == “FIND”) print $2}’

How to debug bash script?

Add -xv to #!/bin/bash
#!/bin/bash –xv

Give an example how to write function ?

function example {
echo “Hello world!”

How to add string to string ?

let V3=$V1+$V2
echo $V3

How to add two integers ?

echo $V3
Remember you need to add “let” to line V3=$V1+$V2
then echo $V3 will give 3
if without let , then it will be
echo $V3 will give 1+2

How to check if file exist on filesystem ?

if [ -f /var/log/messages ]
echo “File exists”

Write down syntax for all loops in shell scripting ?

for loop :
for i in $( ls ); do
echo item: $i
while loop :
while [ $COUNTER -lt 10 ]; do
echo The counter is $COUNTER
until loop :
until [ $COUNTER -lt 10 ]; do
let COUNTER-=1

What it means by #!/bin/sh or #!/bin/bash at beginning of every script ?

That line tells which shell to use. #!/bin/bash script to execute using /bin/bash. In case of python script there there will be #!/usr/bin/python.

How to get 10th line from the text file ?

head -10 file|tail -1

What is the first symbol in the bash script file?


What would be the output of command: `{` -z “” `}` && echo 0 || echo 1?


What command “export” do ?

Makes variable public in subshells.

How to run script in background ?

add “&” to the end of script

What “chmod 500 script” do ?

Makes script executable for script owner.

What “>” do ?

Redirects output stream to file or another stream.

What difference between & and &&?

& – we using it when want to put script to background
&& – when we wand to execute command/script if first script was finished successfully.

When we need “if” before `{` condition `}` ?

When we need to run several commands if condition meets.

What would be the output of the command: name=John && echo ‘My name is $name’?

My name is $name.

Which is the symbol used for comments in bash shell scripting ?


What would be the output of command: echo ${new:-variable}?


What difference between ‘ and ” quotes ?

‘ – we use it when do not want to evaluate variables to the values
” – all variables will be evaluated and its values will be assigned instead.

How to redirect stdout and stderr streams to log.txt file from script inside ?

Add “exec >log.txt 2>&1” as the first command in the script.

How to get part of string variable with echo command only ?

echo ${variable:x:y}
x – start position
y – length
variable=”My name is Petras, and I am developer.”
echo ${variable:11:6} # will display Petras

How to get home_dir with echo command only if string variable=”User:123:321:/home/dir” is given ?

echo ${variable#*:*:*:}
echo ${variable##*:}

How to get “User” from the string above ?

echo ${variable%:*:*:*}
echo ${variable%%:*}

How to list users which UID less that 100 (awk) ?

awk -F: ‘$3<100’ /etc/passwd

Write the program which counts unique primary groups for users and displays count and group name only?

cat /etc/passwd|cut -d: -f4|sort|uniq -c|while read c g
{ echo $c; grep :$g: /etc/group|cut -d: -f1;}|xargs -n 2

How to change standard field separator to “:” in bash shell ?


How to get variable length ?


How to print last 5 characters of variable ?

echo ${variable: -5}

What difference between ${variable:-10} and ${variable: -10} ?

${variable:-10} – gives 10 if variable was not assigned before
${variable: -10} – gives last 10 symbols of variable

How to substitute part of string with echo command only ?

echo ${variable//pattern/replacement}

Which command replaces string to uppercase ?

tr ‘[:lower:]’ ‘[:upper:]’

How to count local accounts ?

wc -l /etc/passwd|cut -d” ” -f1
cat /etc/passwd|wc -l

How to count words in a string without wc command ?

set ${string}
echo $#

Which one is correct “export $variable” or “export variable” ?

export variable

How to list files where second letter is a or b ?

ls -d ?[ab]*

How to add integers a to b and assign to c ?

c=`expr $a + $b`
c=`echo “$a+$b”|bc`

How to remove all spaces from the string ?

echo $string|tr -d ” ”

Rewrite the command to print the sentence and converting variable to plural: item=”car”; echo “I like $item” ?

item=”car”; echo “I like ${item}s”

Write the command which will print numbers from 0 to 100 and display every third (0 3 6 9 …) ?

for i in {0..100..3}; do echo $i; done
for (( i=0; i<=100; i=i+3 )); do echo “Welcome $i times”; done

How to print all arguments provided to the script ?

echo $*
echo [email protected]

What difference between `{` $a == $b `}` and `{` $a -eq $b `}`?

[ $a == $b ] – should be used for string comparison
[ $a -eq $b ] – should be used for number tests

What difference between = and == ?

= – we using to assign value to variable
== – we using for string comparison

Write the command to test if $a greater than 12 ?

[ $a -gt 12 ]

Write the command to test if $b les or equal 12 ?

[ $b -le 12 ]

How to check if string begins with “abc” letters ?

[[ $string == abc* ]]

What difference between `{``{` $string == abc* `}``}` and `{``{` $string == “abc*” `}``}`?

[[ $string == abc* ]] – will check if string begins with abc letters
[[ $string == “abc*” ]] – will check if string is equal exactly to abc*

How to list usernames which starts with ab or xy ?

egrep “^ab|^xy” /etc/passwd|cut -d: -f1

What $! means in bash ?

Most recent background command PID

What $? means ?

Most recent foreground exit status.

How to print PID of the current shell ?

echo $$

How to get number of passed arguments to the script ?

echo $#

What difference between $* and [email protected]?

$* – gives all passed arguments to the script as a single string
[email protected] – gives all passed arguments to the script as delimited list. Delimiter $IFS

How to define array in bash ?

array=(“Hi” “my” “name” “is”)

How to print the first array element ?

echo ${array[0]}

How to print all array elements ?

echo ${array[@]}

How to print all array indexes ?

echo ${!array[@]}

How to remove array element with id 2 ?

unset array[2]

How to add new array element with id 333 ?


How shell script get input values ?

via parameters
./script param1 param2
b) via read command
read -p “Destination backup Server : ” desthost

How can we use “expect” command in a script ?

/usr/bin/expect << EOD
spawn rsync -ar ${line} ${desthost}:${destpath}
expect “*?assword:*”
send “${password}\r”
expect eof

What are the different types of commonly used shells on a typical linux system?

csh,ksh,bash,Bourne . The most commonly used and advanced shell used today is “Bash” .

What is the equivalent of a file shortcut that we have on window on a Linux system?

Shortcuts are created using “links” on Linux. There are two types of links that can be used namely “soft link” and “hard link”

What is the difference between soft and hard links?

Soft links are link to the file name and can reside on different filesytem as well; however hard links are link to the inode of the file and has to be on the same filesytem as that of the file. Deleting the orginal file makes the soft link inactive (broken link) but does not affect the hard link (Hard link will still access a copy of the file)

How will you pass and access arguments to a script in Linux?

Arguments can be passed as:

scriptName “Arg1” “Arg2”….”Argn” and can be accessed inside the script as $1 , $2 .. $n

What is the significance of $#?

$# shows the count of the arguments passed to the script.

What is the difference between $* and [email protected]?

[email protected] treats each quoted arguments as separate arguments but $* will consider the entire set of positional parameters as a single string.

Use sed command to replace the content of the file (emulate tac command)?



Then O/p should be


Here G command appends to the pattern space,

h command copies pattern buffer to hold buffer

and d command deletes the current pattern  space.

Given a file, replace all occurrence of word “ABC” with “DEF” from 5th line till end in only those lines that contains word “MNO”?

sed –n ‘5,$p’ file1|sed ‘/MNO/s/ABC/DEF/

Given a file , write a command sequence to find the count of each word?


”(backslash)011” is octal equivalent of “tab character” and

“(backslash)012” is octal equivalent of newline character.

How will you find the 99th line of a file using only tail and head command?

tail +99 file1|head -1

Explain about “s” permission bit in a file?

“s” bit is called “set user id” (SUID) bit.

“s” bit on a file causes the process to have the privileges of the owner of the file during the instance of the program.

Eg: Executing “passwd” command to change current password causes the user to writes its new password to shadow file even though it has “root” as its owner.

I want to create a directory such that anyone in the group can create a file and access any person’s file in it but none should be able to delete a file other than the one created by himself ?

We can create the directory giving read and execute access to everyone in the group and setting its sticky bit “t” on as follows:

How can you find out how long the system has been running?

Command “uptime”

How can any user find out all information about a specific user like his default shell, real life name, default directory,when and how long he has been using the sytem?

finger  “loginName”                  …where loginName is the  login name of  the

user whose  information is expected.

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 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.

How will you copy file from one machine to other?

We can use utilities like “ftp” ,”scp” or “rsync” to copy file from one machine to other.

Eg: Using ftp:

ftp hostname

>put file1


Above copies file file1 from local system to destination system whose hostname is specified.

I want to monitor a continuously updating log file, what command can be used to most efficiently achieve this?

We can use tail –f filename     . This will cause only the default last 10 lines to be displayed on std o/p which continuously shows  the updating part of the file.

I want to connect to a remote server and execute some commands, how can I achieve this?

We can use telnet to do this:

telnet hostname –l user

>Enter password

>Write the command to execute


I have 2 files and I want to print the records which are common to both?

We can use “comm” command as follows:

comm -12 file1 file2               … 12 will suppress the content which are

unique to 1st and 2nd  file respectively.

Write a script to print the first 10 elemenst of Fibonacci series?


echo $a
echo $b
for I in 1 2 3 4 5 6 7 8
echo $b

How will you connect to a database server from linux?

We can use isql utility that comes with open client driver  as follows:

isql –S serverName –U username –P password

What are the 3 standard streams in Linux?

0 – Standard Input
1 – Standard Output
2 – Standard Error

I want to read all input to the command from file1 direct all output to file2 and error to file 3, how can I achieve this?

command <file1 1>file2 2>file3

What will happen to my current process when I execute a command using exec?

“exec” overlays the newly forked process on the current  process ; so when I execute the command using exec, the command gets executed on the current shell without creating any new processes.

Eg: Executing “exec  ls”  on command prompt will execute ls and once ls exits, the process will shut down.

How will you emulate wc –l using awk?

grep –c  “ABC” file1

What is the difference between grep and egrep?

egrep is Extended grep that supports added grep features like “+” (1 or more occurrence of previous character),”?”(0 or 1 occurrence of previous character) and “|” (alternate matching).

How will you print the login names of all users on a system?

/etc/shadow file has all the users listed.

awk –F ‘:’ ‘{print $1} /etc/shadow’|uniq -u

How to set an array in Linux?

Syntax in ksh:

Set –A arrayname= (element1 element2 ….. element)

In bash

A=(element1 element2 element3 …. elementn)

Write down the syntax of “for “ loop?


for  iterator in (elements)


execute commands


How will you find the total disk space used by a specific user?

du  -s /home/user1             ….where user1 is the user for whom the total disk

space needs to be found.

Write the syntax for “if” conditionals in linux?


If  condition is successful


execute commands


execute commands


What is the significance of $? ?

$? gives the exit status of the last command that was executed.

How will I insert a line “ABCDEF” at every 100th line of a file?

sed ‘100i\ABCDEF’ file1

Write a command sequence to find all the files modified in less than 2 days and print the record count of each?

find . –mtime -2 –exec wc –l {} \;

How can we find the process name from its process id?

We can use “ps –p ProcessId”

What are the four fundamental components of every file system on linux?

bootblock, super block, inode block and  datablock

What is a boot block?

This block contains a small program called “Master Boot record”(MBR) which loads the kernel  during system boot up.

Review Date
Reviewed Item
Nice!! Linux Shell Scripting Interview Questions and Answers Keep Adding More Please.
Author Rating